console
var canvas = document.getElementById('canvas');
canvas.width = 400;
canvas.height = 400;
if (canvas.getContext('2d')) {
var tangram = [
{ p: [{ x: 0, y: 0 }, { x: 0, y: 400 }, { x: 200, y: 200 }, { x: 0, y: 0 }], color: "#5eb6d0" },
{ p: [{ x: 0, y: 0 }, { x: 400, y: 0 }, { x: 200, y: 200 }, { x: 0, y: 0 }], color: "#cbf162" },
{ p: [{ x: 0, y: 400 }, { x: 100, y: 300 }, { x: 200, y: 400 }, { x: 0, y: 400 }], color: "#fe9cce" },
{ p: [{ x: 200, y: 400 }, { x: 100, y: 300 }, { x: 200, y: 200 }, { x: 300, y: 300 }, { x: 200, y: 400 }], color: "#a798c4" },
{ p: [{ x: 200, y: 200 }, { x: 300, y: 100 }, { x: 300, y: 300 }, { x: 200, y: 200 }], color: "#fdea11" },
{ p: [{ x: 300, y: 100 }, { x: 400, y: 0 }, { x: 400, y: 200 }, { x: 300, y: 300 }, { x: 300, y: 100 }], color: "#ff5062" },
{ p: [{ x: 200, y: 400 }, { x: 400, y: 200 }, { x: 400, y: 400 }, { x: 200, y: 400 }], color: "#fcc520" },
];
var context = canvas.getContext('2d');
for (p of tangram) {
draw(p, context);
}
function draw(piece, context) {
context.beginPath();
// 起始点
context.moveTo(piece.p[0].x, piece.p[0].y);
for (var i = 1; i < piece.p.length; i++) {
context.lineTo(piece.p[i].x, piece.p[i].y);
}
context.closePath();
// 填充颜色
context.fillStyle = piece.color;
context.fill()
}
// 线条宽度
// context.lineWidth=5;
// 线条颜色
// context.strokeStyle="#ccc"
// context.stroke();
} else {
alert('您的浏览器不支持Canvas,请使用高版本浏览器');
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>canvas绘制七巧板</title>
</head>
<body>
<canvas id="canvas" width="400" height="400" style="display:block;margin:30px auto; border:1px solid #ccc;">
您的浏览器不支持Canvas,请使用高版本浏览器
</canvas>
</body>
</html>