I try to change a image by changing the image.src. But it doesn't work. When it is used in setInterval() function, it works. I wan t know WHY(?).
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();
}
I have heard of 'preload of images before uses'. But I don't know exactly. Anyway the written below works. Then why don't they need the preload? (Excuse my ignorance)
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() {
draw(1); }