为了账号安全,请及时绑定邮箱和手机立即绑定

两个html文件分别放一个canvas,用同一个js文件,第二个html文件的canvas画不出画是咋回事?

两个html文件分别放一个canvas,用同一个js文件,第二个html文件的canvas画不出画是咋回事?

var canvas = document.getElementById('myCanvas');

var ctx = canvas.getContext('2d');

var pieces = [

{p:[{x:0, y:0}, {x:400, y:400}, {x:0, y:800}], color:'#FF0000'},

{p:[{x:0, y:0}, {x:400, y:400}, {x:800, y:0}], color:'#FFE32C'},

{p:[{x:0, y:800}, {x:200, y:600}, {x:400, y:800}], color:'#21D4FD'},

{p:[{x:400, y:800}, {x:800, y:400}, {x:800, y:800}], color:'#FAACA8'},

{p:[{x:400, y:400}, {x:600, y:600}, {x:400, y:800}, {x:200, y:600}], color:'#08AEEA'},

{p:[{x:400, y:400}, {x:600, y:600}, {x:600, y:200}], color:'#FA709A'},

{p:[{x:600, y:600}, {x:600, y:200}, {x:800, y:0}, {x:800, y:400}], color:'#2AF598'},

];

function draw(pieces, ctx){

ctx.save();

for(var i = 0 ; i < pieces.length ; i++){

ctx.beginPath();

ctx.moveTo(pieces[i].p[0].x, pieces[i].p[0].y);

for(var j = 1 ; j < pieces[i].p.length ; j++){

ctx.lineTo(pieces[i].p[j].x, pieces[i].p[j].y);

}

ctx.closePath();

ctx.fillStyle = pieces[i].color;

ctx.fill();

}

}


draw(pieces, ctx);//这个是第一个html文件的canvas



var canvas1 = document.getElementById('myCanvas1');

var ctx1 = canvas1.getContext('2d');

function draw1(){

ctx1.translate(400, 400);

ctx1.beginPath();

ctx1.arc(0, 0, 200, 0, 2 * Math.PI, false);

ctx1.lineWidth = 5;

ctx1.strokeStyle = '#BE0707';

ctx1.stroke();

ctx.restore();

}


draw1();//这个是第二个html文件的canvas,画不出来


正在回答

1 回答

这个是代码

var canvas = document.getElementById('myCanvas');


var ctx = canvas.getContext('2d');


var pieces = [

{p:[{x:0, y:0}, {x:400, y:400}, {x:0, y:800}], color:'#FF0000'},

{p:[{x:0, y:0}, {x:400, y:400}, {x:800, y:0}], color:'#FFE32C'},

{p:[{x:0, y:800}, {x:200, y:600}, {x:400, y:800}], color:'#21D4FD'},

{p:[{x:400, y:800}, {x:800, y:400}, {x:800, y:800}], color:'#FAACA8'},

{p:[{x:400, y:400}, {x:600, y:600}, {x:400, y:800}, {x:200, y:600}], color:'#08AEEA'},

{p:[{x:400, y:400}, {x:600, y:600}, {x:600, y:200}], color:'#FA709A'},

{p:[{x:600, y:600}, {x:600, y:200}, {x:800, y:0}, {x:800, y:400}], color:'#2AF598'},


];



function draw(pieces, ctx){

for(var i = 0 ; i < pieces.length ; i++){

ctx.beginPath();

ctx.moveTo(pieces[i].p[0].x, pieces[i].p[0].y);

for(var j = 1 ; j < pieces[i].p.length ; j++){

ctx.lineTo(pieces[i].p[j].x, pieces[i].p[j].y);

}

ctx.closePath();

ctx.fillStyle = pieces[i].color;

ctx.fill();

}

}


draw(pieces, ctx);



var canvas1 = document.getElementById('myCanvas1');

var ctx1 = canvas1.getContext('2d');

function draw1(){

ctx1.translate(400, 400);

ctx1.beginPath();

ctx1.arc(0, 0, 200, 0, 2 * Math.PI, false);

ctx1.lineWidth = 5;

ctx1.strokeStyle = '#BE0707';

ctx1.stroke();

}


draw1();


0 回复 有任何疑惑可以回复我~

举报

0/150
提交
取消

两个html文件分别放一个canvas,用同一个js文件,第二个html文件的canvas画不出画是咋回事?

我要回答 关注问题
意见反馈 帮助中心 APP下载
官方微信