添加画布
1 <canvas id="myCanvas" width="200" height="100"></canvas>
通过javascript来绘制
1 <script type="text/javascript">
2 var c=document.getElementById("myCanvas");
3 var cxt=c.getContext("2d");
4 cxt.fillStyle="#FF0000";
5 cxt.fillRect(0,0,150,75);
6 </script>
2 var c=document.getElementById("myCanvas");
3 var cxt=c.getContext("2d");
4 cxt.fillStyle="#FF0000";
5 cxt.fillRect(0,0,150,75);
6 </script>
getContext("2d") 对象是内建的 HTML5 对象,拥有多种绘制路径、矩形、圆形、字符以及添加图像的方法。
下面的两行代码绘制一个红色的矩形:
1 cxt.fillStyle="#FF0000";
2 cxt.fillRect(0,0,150,75);
2 cxt.fillRect(0,0,150,75);
下面代码画线
1 <script type="text/javascript">
2
3 var c=document.getElementById("myCanvas");
4 var cxt=c.getContext("2d");
5 cxt.moveTo(10,10);
6 cxt.lineTo(150,50);
7 cxt.lineTo(10,50);
8 cxt.stroke();
9
10 </script>
2
3 var c=document.getElementById("myCanvas");
4 var cxt=c.getContext("2d");
5 cxt.moveTo(10,10);
6 cxt.lineTo(150,50);
7 cxt.lineTo(10,50);
8 cxt.stroke();
9
10 </script>
圆形
1 <script type="text/javascript">
2
3 var c=document.getElementById("myCanvas");
4 var cxt=c.getContext("2d");
5 cxt.fillStyle="#FF0000";
6 cxt.beginPath();
7 cxt.arc(70,18,15,0,Math.PI*2,true);
8 cxt.closePath();
9 cxt.fill();
10
11 </script>
2
3 var c=document.getElementById("myCanvas");
4 var cxt=c.getContext("2d");
5 cxt.fillStyle="#FF0000";
6 cxt.beginPath();
7 cxt.arc(70,18,15,0,Math.PI*2,true);
8 cxt.closePath();
9 cxt.fill();
10
11 </script>
渐变
1 <script type="text/javascript">
2
3 var c=document.getElementById("myCanvas");
4 var cxt=c.getContext("2d");
5 var grd=cxt.createLinearGradient(0,0,175,50);
6 grd.addColorStop(0,"#FF0000");
7 grd.addColorStop(1,"#00FF00");
8 cxt.fillStyle=grd;
9 cxt.fillRect(0,0,175,50);
10
11 </script>
2
3 var c=document.getElementById("myCanvas");
4 var cxt=c.getContext("2d");
5 var grd=cxt.createLinearGradient(0,0,175,50);
6 grd.addColorStop(0,"#FF0000");
7 grd.addColorStop(1,"#00FF00");
8 cxt.fillStyle=grd;
9 cxt.fillRect(0,0,175,50);
10
11 </script>
图片
1 <script type="text/javascript">
2
3 var c=document.getElementById("myCanvas");
4 var cxt=c.getContext("2d");
5 var img=new Image()
6 img.src="flower.png"
7 cxt.drawImage(img,0,0);
8
9 </script>
2
3 var c=document.getElementById("myCanvas");
4 var cxt=c.getContext("2d");
5 var img=new Image()
6 img.src="flower.png"
7 cxt.drawImage(img,0,0);
8
9 </script>