1.画矩形(红色)

 1 <body>
 2 
 3 <canvas id="myCanvas" width="200" height="100">
 4 </canvas>
 5 <script type="text/javascript">
 6 var c=document.getElementById("myCanvas");
 7 var cxt= c.getContext("2d");
 8 cxt.fillStyle="#FF0000";
 9 cxt.fillRect(0,0,150,75);
10 </script>
11 </body>

2.画三角形

<body>
<canvas id="myCanvas1" width="200" height="100" style="border:1px solid #c3c3c3;">
Your DDDDDD</canvas>
<script type="text/javascript">
var c=document.getElementById("myCanvas1");
var cxt=c.getContext("2d");
cxt.moveTo(10,10);
cxt.lineTo(150,50);
cxt.lineTo(10,50);
cxt.lineTo(10,10);
cxt.stroke();
</script>
</body>

 3.画圆并填充颜色

 1 <body>
 2 <canvas id="myCanvas2" width="200" height="100" style="border:1px solid #c3c3c3;"></canvas>
 3 <script type="text/javascript">
 4 var c=document.getElementById("myCanvas2");
 5 var cxt=c.getContext("2d");
 6 cxt.fillStyle="FF0000";
 7 cxt.beginPath();
 8 cxt.arc(70,18,15,0,Math.PI*2,true);
 9 cxt.closePath();
10 cxt.fill();
11 
12 </script>
13 
14 </body>

 4.颜色渐变

 1 <body><canvas id="myCanvas3" width="200" height="100" style="border:1px solid #c3c3c3;">
 2 Your broswer does not support the canvas element.
 3 </canvas>
 4 
 5 <script type="text/javascript">
 6 var c=document.getElementById("myCanvas3");
 7 var cxt=c.getContext("2d");
 8 var grd=cxt.createLinearGradient(0,0,175,50);
 9 grd.addColorStop(0,"#FF0000");
10 grd.addColorStop(1,"#00FF00");
11 cxt.fillStyle=grd;
12 cxt.fillRect(0,0,175,50);
13 </script>
14 </body>

 5.插入图片(注意图片尺寸)

 1 <body>
 2 <canvas id="myCanvas4" width="400" height="600" style="border:1px solid #c3c3c3;">
 3 Your broswer does not support the canvas element.
 4 
 5 </canvas>
 6 
 7 <script type="text/javascript">
 8 var c=document.getElementById("myCanvas4");
 9 var cxt=c.getContext("2d");
10 var img=new Image();
11 img.src="images/apple.jpg";
12 
13 img.onload=function(){
14      cxt.drawImage(img,0,0);
15 }
16 
17 </script>
18 
19 
20 </body>

 

版权声明:本文为zijue原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/zijue/p/9881408.html