canvas绘制七巧板

效果如下所示:

canvas绘制七巧板

代码分享:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Canvas七巧板</title> </head> <body> <canvas></canvas> <script type="text/javascript"> var tangram = [ {p:[{x:0,y:0},{x:800,y:0},{x:400,y:400}],color:'#caff67'}, {p:[{x:0,y:0},{x:400,y:400},{x:0,y:800}],color:'#67becf'}, {p:[{x:800,y:0},{x:800,y:400},{x:600,y:600},{x:600,y:200}],color:'#ef3d61'}, {p:[{x:600,y:200},{x:600,y:600},{x:400,y:400}],color:'#f9f51a'}, {p:[{x:400,y:400},{x:600,y:600},{x:400,y:800},{x:200,y:600}],color:'#a594c0'}, {p:[{x:200,y:600},{x:400,y:800},{x:0,y:800}],color:'#fa8ecc'}, {p:[{x:800,y:400},{x:800,y:800},{x:400,y:800}],color:'#f6ca29'} ] // 定义一个存放绘制路径和颜色的数组 window.onload=function (){ var canvas=document.getElementById('canvas'); // 获取canvas canvas.width = 800; canvas.height = 800; // 定义画布的宽高 var context=canvas.getContext('2d'); // 创建画布 for( var i=0; i<tangram.length; i++){ draw(tangram[i],context); // 遍历数组tangram执行函数draw } // draw这个函数 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++) // 遍历数组中的p属性 cxt.lineTo(piece.p[i].x , piece.p[i].y); // 画路径到这个坐标 cxt.closePath(); // 关闭这条打开的路径 cxt.fillStyle = piece.color; cxt.fill(); // 给绘制的形状填充颜色 } } </script> </body> </html>

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wwgsfs.html