Purplefly
2016-10-31 21:50
<!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>
我们如果把函数按照数组循环完调用draw()i次后 代码相当于下面
moveTo(0,0)
lineTo(200,200)
lineTo(400,0)
fill();//第一次画完没有颜色
/* fillStyle("arr[0].color")//重点看这里,这是第二个图形的轨迹,这里的fillstyle取得是第一个里面的颜色 fillstyle可以写在moveTo的前面是所以颜色后移
moveTo(0,0)
lineTo(200,200)
lineTo(0,400)
fill();*/
/*fillStyle("arr[1].color")
moveTo(0,0)
lineTo(200,200)
lineTo(400,0)
fill();*/
fillStyle("arr[2].color")
..........
炫丽的倒计时效果Canvas绘图与动画基础
96746 学习 · 1000 问题
相似问题