context在这里是全局变量吧,那么是不是在draw函数中就可以直接使用context来进行绘制了,为什么还要在把context的值传给cxt呢?求指点
$("#tangram").bind("click",function tangram() {
var canvas = document.getElementById("canvas");
canvas.width = 800;
canvas.height = 700;
if (canvas.getContext("2d")) {
var context = canvas.getContext("2d");
}
else {
alert("当前浏览器不支持Canvas,推荐使用Chrome浏览器")
}
var tangram=[
{p:[{x:0,y:0},{x:800,y:0},{x:400,y:400}],color:"red"},
{p:[{x:0,y:0},{x:400,y:400},{x:0,y:800}],color:"yellow"},
{p:[{x:0,y:0},{x:800,y:0},{x:400,y:400}],color:"red"},
{p:[{x:0,y:0},{x:800,y:0},{x:400,y:400}],color:"red"},
{p:[{x:0,y:0},{x:800,y:0},{x:400,y:400}],color:"red"},
{p:[{x:0,y:0},{x:800,y:0},{x:400,y:400}],color:"red"},
{p:[{x:0,y:0},{x:800,y:0},{x:400,y:400}],color:"red"},
]
for (var i=0;i<tangram.length;i++){
draw(tangram[i]);
}
function draw(piece){
context.beginPath();
context.moveTo(piece.p[0].x,piece.p[0].y);
for (var i=1;i<piece.length;i++){
context.lineTo(piece[i].x,piece[i].y);
}
context.closePath();
context.fillStyle=tangram[0].color;
context.fill();
}