【canvas】 绘制七巧板
效果图:
代码 :
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title></title> </head> <body> <canvas id="canvas" width="600" height="600" style="border-radius: 10px;">您的浏览器不支持canvas,请更换浏览器</canvas> <script> let canvas = document.getElementById("canvas"); let datas = [ { p:[ {x:0,y:0},{x:600,y:0},{x:300,y:300} ], color:"#3498db" }, { p:[ {x:0,y:0},{x:0,y:600},{x:300,y:300} ], color:"#f1c40f" }, { p:[ {x:0,y:600},{x:300,y:600},{x:150,y:450} ], color:"#e67e22" }, { p:[ {x:150,y:450},{x:300,y:300},{x:450,y:450},{x:300,y:600} ], color:"#e74c3c" }, { p:[ {x:300,y:600},{x:600,y:300},{x:600,y:600},{x:300,y:600} ], color:"#9b59b6" }, { p:[ {x:600,y:300},{x:450,y:450},{x:300,y:300},{x:450,y:150},{x:600,y:300} ], color:"#2c3e50" }, { p:[ {x:600,y:0},{x:600,y:300},{x:450,y:150} ], color:"#95a5a6" }, ] if(canvas.getContext("2d")){ let context = canvas.getContext("2d"); for (let i = 0; i < datas.length; i++) { seniorDraw(datas[i].p,datas[i].color,context); } } function seniorDraw(pies,color,context){ context.beginPath(); context.moveTo(pies[0].x,pies[0].y); for (let i = 1; i < pies.length; i++) { context.lineTo(pies[i].x,pies[i].y); } context.closePath(); context.fillStyle = color; context.fill(); } // 普通绘制 function ordinaryDraw(){ let context = canvas.getContext("2d"); context.beginPath(); context.moveTo(0,0); context.lineTo(600,0); context.lineTo(300,300); context.closePath(); context.fillStyle = "#3498db"; context.fill(); context.beginPath(); context.moveTo(0,0); context.lineTo(0,600); context.lineTo(300,300); context.closePath(); context.fillStyle = "#f1c40f"; context.fill(); context.beginPath(); context.moveTo(0,600); context.lineTo(300,600); context.lineTo(150,450); context.closePath(); context.fillStyle = "#e67e22"; context.fill(); context.beginPath(); context.moveTo(150,450); context.lineTo(300,300); context.lineTo(450,450); context.lineTo(300,600); context.closePath(); context.fillStyle = "#e74c3c"; context.fill(); context.beginPath(); context.moveTo(300,600); context.lineTo(600,300); context.lineTo(600,600); context.lineTo(300,600); context.closePath(); context.fillStyle = "#9b59b6"; context.fill(); context.beginPath(); context.moveTo(600,300); context.lineTo(450,450); context.lineTo(300,300); context.lineTo(450,150); context.lineTo(600,300); context.closePath(); context.fillStyle = "#2c3e50"; context.fill(); context.beginPath(); context.moveTo(600,0); context.lineTo(600,300); context.lineTo(450,150); context.closePath(); context.fillStyle = "#95a5a6"; context.fill(); } </script> </body> </html>