GitHub: https://github.com/BadWaka/canvas-study/blob/master/public/2-2/tangram.html
參考視頻:慕課網(wǎng)-炫麗的倒計時效果Canvas繪圖與動畫基礎(chǔ)-繪制直線爬骤、多邊形和七巧板-慕課網(wǎng)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>七巧板</title>
</head>
<body>
<canvas id="tangram"></canvas>
<script>
// 數(shù)據(jù)數(shù)組
var tangramArr = [
{coordinateArr: [{x: 0, y: 0}, {x: 800, y: 0}, {x: 400, y: 400}], color: '#caff67'},
{coordinateArr: [{x: 0, y: 0}, {x: 400, y: 400}, {x: 0, y: 800}], color: '#67becf'},
{coordinateArr: [{x: 800, y: 0}, {x: 800, y: 400}, {x: 600, y: 600}, {x: 600, y: 200}], color: '#ef3d61'},
{coordinateArr: [{x: 600, y: 200}, {x: 600, y: 600}, {x: 400, y: 400}], color: '#f9f51a'},
{coordinateArr: [{x: 400, y: 400}, {x: 600, y: 600}, {x: 400, y: 800}, {x: 200, y: 600}], color: '#a594c0'},
{coordinateArr: [{x: 200, y: 600}, {x: 400, y: 800}, {x: 0, y: 800}], color: '#fa8ecc'},
{coordinateArr: [{x: 800, y: 400}, {x: 800, y: 800}, {x: 400, y: 800}], color: '#caff67'},
];
window.onload = function () {
var canvas = document.getElementById('tangram');
canvas.width = 800;
canvas.height = 800;
var ctx = canvas.getContext('2d');
tangramArr.forEach(function (item, index) {
draw(item, ctx);
});
};
function draw(item, ctx) {
var coordinateArr = item.coordinateArr;
var color = item.color;
ctx.beginPath(); // beginPath方法類似于開啟新的路徑繪畫或清空已有路徑
ctx.moveTo(coordinateArr[0].x, coordinateArr[0].y);
for (var i = 1; i < coordinateArr.length; i++) {
ctx.lineTo(coordinateArr[i].x, coordinateArr[i].y);
}
ctx.closePath(); // closePath并不是用來表示結(jié)束 而是功能性的 做圖形閉合處理(從最后的狀態(tài)點自動lineTo回歸起始點封口)
ctx.fillStyle = color;
ctx.fill();
}
</script>
</body>
</html>