2014-02-08 80 views
0

我尝试通过更改image.src来更改图像。 但它不起作用。当它在setInterval()函数中使用时,它可以工作。我知道 我知道为什么(?)。画布图像更改通过更改src

var imgE=new Image(); 
imgE.src="Ship.png"; 
window.onload=init; 

function init() { 
ctx=document.getElementById("can1").getContext("2d"); 
draw(); 
//setInterval(draw,100); 
butE=document.getElementsByTagName("button"); 
butE[0].onclick=change; 
butE[1].onclick=getback; 
} 

function draw() { 
    ctx.clearRect(0,0,800,500); 
    ctx.drawImage(imgE,100,100,100,100); 
} 
function change() { 
    imgE.src="Ship_d.png"; 
    draw(); 
} 
function getback() { 
    imgE.src="Ship.png"; 
    draw(); 
} 

我听说过'使用前图像预加载'。但我不完全清楚。 无论如何,下面的书面作品。那为什么他们不需要预加载呢? (请原谅我无知)

var imgE=new Image(); 
imgE.src="Ship.png"; 
var imgdE=new Image(); 
imgdE.src="Ship_d.png"; 
window.onload=init; 

function init() { 
ctx=document.getElementById("can1").getContext("2d"); 
draw(1); 
butE=document.getElementsByTagName("button"); 
butE[0].onclick=change; 
butE[1].onclick=getback; 
} 

function draw(no) { 
ctx.clearRect(0,0,800,500); 
    if (no==1) { 
    ctx.drawImage(imgE,100,100,100,100); 
    } 
    else ctx.drawImage(imgdE,100,100,100,100); 
} 
function change() { 
draw(2); 
} 
function getback() { 

拉伸(1); }

+0

请加与此相关的代码的HTML部分之前所需要的图像。 – celerno

+0

[Javascript set img src]可能的重复(http://stackoverflow.com/questions/1232793/javascript-set-img-src) – celerno

回答

2

这很可能是因为图像没有及时加载。

要么预装你使用它们,或者你需要使用

imgE.src = "Ship_d.png"; 
imgE.onload = draw; 
+0

我添加了第二个问题,通过编辑原始问题来解决您的问题。 – user3285913

+0

我不知道你在问你的新问题。 – epascarello