context在這里是全局變量吧,那么是不是在draw函數(shù)中就可以直接使用context來進(jìn)行繪制了,為什么還要在把context的值傳給cxt呢?求指點(diǎn)
$("#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("當(dāng)前瀏覽器不支持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();
? ?}
2015-01-23
我的理解是對的,之所以沒畫出來,我的代碼錯(cuò)在這里了:
for (var i=1;i<piece.length;i++){
? ? ? ? ? ?context.lineTo(piece[i].x,piece[i].y);
? ? ? ?}
應(yīng)該是
i<piece.p.length
context.lineTo(piece.p[i].x,piece.p[i].y)