为什么把加粗这一行写到ctx.fill()后面会造成颜色的顺序后移,我懂第一个三角形由于代码顺序会没有颜色值但后面的不清楚。。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>七巧板</title>
</head>
<body>
<canvas id="canvas" width="400" height="400" ></canvas>
<script>
var canvas = document.getElementById('canvas');
var tangram = [{p:[{x:0,y:0},{x:200,y:200},{x:400,y:0}],color:"#ffff00"}, //黄
{p:[{x:0,y:0},{x:200,y:200},{x:0,y:400}],color:"#ffc0cb"}, //浅紫色
{p:[{x:300,y:100},{x:200,y:200},{x:300,y:300}],color:"#0000ff"}, //蓝色
{p:[{x:300,y:100},{x:400,y:0},{x:400,y:200},{x:300,y:300}],color:"#800080"}, //紫色
{p:[{x:200,y:200},{x:100,y:300},{x:200,y:400},{x:300,y:300}],color:"#ff0000"}, //红色
{p:[{x:0,y:400},{x:100,y:300},{x:200,y:400}],color:"#008000"}, //绿色
{p:[{x:200,y:400},{x:400,y:400},{x:400,y:200}],color:"#add8e6"}, //淡蓝色
]
function draw(ctx,attr){
ctx.beginPath();
ctx.moveTo(attr.p[0].x,attr.p[0].y);
for(var i=1;i<attr.p.length;i++){
ctx.lineTo(attr.p[i].x,attr.p[i].y);
}
ctx.fillStyle = attr.color;
ctx.fill();
ctx.closePath();
}
window.onload = function(){
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
for(var i=0;i<tangram.length;i++){
draw(context,tangram[i]);
}
}
</script>
</body>
</html>