<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>canvas数组绘制七巧板</title> </head> <body> <canvas id="canvas" style="border:1px solid #aaa; margin:50px auto; display:block;"></canvas> <script> var tangram=[ {p:[{x:0,y:0},{x:600,y:0},{x:300,y:300}],color:"#caff67"}, {p:[{x:0,y:0},{x:300,y:300},{x:0,y:600}],color:"#67becf"}, {p:[{x:600,y:600},{x:600,y:300},{x:600,y:600},{x:600,y:150}],color:"#ef3d61"}, {p:[{x:600,y:150},{x:600,y:600},{x:300,y:300}],color:"#a594c0"}, {p:[{x:300,y:300},{x:600,y:600},{x:300,y:600},{x:150,y:600}],color:"#fa8ccc"}, {p:[{x:150,y:600},{x:300,y:600},{x:0,y:600}],color:"#f6ca29"}, {p:[{x:600,y:300},{x:600,y:600},{x:300,y:600}],color:"#f5f91a"}, ] window.onload=function(){ var canvas=document.getElementById('canvas'); canvas.width=600; canvas.height=600; var context=canvas.getContext("2d"); for(var i=0;i<tangram.length;i++) //数组遍历 draw(tangram[i].context); } function draw(piece,cxt){ cxt.beginPath(); cxt.moveTo(piece.p[0].x,piece.p[0].y); for(var i=1;i<piece.p.length;i++) cxt.lineTo(piece.p[i].x,piece.p[i].y); cxt.closePath(); cxt.fillStyle=piece.color; cxt.fill(); cxt.stroekStyle="blank"; cxt.lineWidth=3; cxt.stroke(); } </script> </body> </html>
Amumu
相关分类