怎么样使用Canvas绘制七巧板?
效果如下所示:
代码分享:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Canvas七巧板</title> </head> <body> <canvas id="canvas" style=" border: 1px solid #aaa;display:block;margin:50px auto;"></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>
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持路饭!
本文地址:http://www.45fan.com/bcdm/88029.html