1 <!DOCTYPE html> 2 <html> 3 <head lang="en"> 4 <meta charset="UTF-8"> 5 <title>绘制多个路径</title> 6 </head> 7 <body> 8 <canvas id="canvas" style="border:1px solid #aaa; display:block;margin:30px auto;"> 9 当前浏览器不支持Canvas,请更换浏览器 10 </canvas> 11 <script> 12 var canvas=document.getElementById('canvas'); 13 canvas.width=1024; 14 canvas.height=768;//也可以在这里设置width和height 15 var context=canvas.getContext('2d'); 16 //使用context进行绘制 17 18 context.beginPath(); 19 context.moveTo(100,100); 20 context.lineTo(700,700); 21 context.lineTo(100,700); 22 context.lineTo(100,100); 23 context.closePath(); 24 25 context.lineWidth=5; 26 context.strokeStyle="red"; 27 context.stroke(); 28 29 context.beginPath(); 30 context.moveTo(200,100); 31 context.lineTo(700,600); 32 context.closePath(); 33 context.strokeStyle="black"; 34 context.stroke(); 35 </script> 36 <!-- 37 1.多个路径需用context.beginPath();和context.closePath();包裹起来,否则上面的样式会被下面覆盖 38 --> 39 </body> 40 </html>
实例:制作七巧板
1 <!DOCTYPE html> 2 <html> 3 <head lang="en"> 4 <meta charset="UTF-8"> 5 <title>制作七巧板</title> 6 </head> 7 <body> 8 <canvas id="canvas" style="border:1px solid #aaa; display:block;margin:50px auto;"> 9 当前浏览器不支持Canvas,请更换浏览器 10 </canvas> 11 <script> 12 var tangram=[ 13 {p:[{x:0,y:0},{x:800,y:0},{x:400,y:400}],color:"#caff67"}, 14 {p:[{x:0,y:0},{x:400,y:400},{x:0,y:800}],color:"#67becf"}, 15 {p:[{x:800,y:0},{x:800,y:400},{x:600,y:600},{x:600,y:200}],color:"#ef3d61"}, 16 {p:[{x:600,y:200},{x:600,y:600},{x:400,y:400}],color:"#f9f51a"}, 17 {p:[{x:400,y:400},{x:600,y:600},{x:400,y:800},{x:200,y:600}],color:"#a594c0"}, 18 {p:[{x:200,y:600},{x:400,y:800},{x:0,y:800}],color:"#fa8eee"}, 19 {p:[{x:800,y:400},{x:800,y:800},{x:400,y:800}],color:"#f6ca29"} 20 ] 21 window.onload=function(){ 22 var canvas=document.getElementById("canvas"); 23 canvas.width=800; 24 canvas.height=800; 25 var context=canvas.getContext("2d"); 26 for(var i=0;i<tangram.length;i++){ 27 draw(tangram[i],context) 28 } 29 } 30 function draw(piece,cxt){ 31 cxt.beginPath(); 32 cxt.moveTo(piece.p[0].x,piece.p[0].y); 33 for(var i=1;i<piece.p.length;i++){ 34 cxt.lineTo(piece.p[i].x,piece.p[i].y); 35 } 36 cxt.fillStyle=piece.color; 37 cxt.fill(); 38 39 cxt.strokeStyle="black"; 40 cxt.lineWidth=3; 41 cxt.stroke(); 42 } 43 </script> 44 45 </body> 46 </html>
效果如下: