0

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); }

2
  • please add the html portion related to this code. Commented Feb 8, 2014 at 0:17
  • possible duplicate of Javascript set img src Commented Feb 8, 2014 at 0:18

1 Answer 1

2

It is most likely because the image is not loaded in time.

Either preload the images needed before you use them or you need to use

imgE.src = "Ship_d.png";
imgE.onload = draw;
Sign up to request clarification or add additional context in comments.

2 Comments

I added a second question relating your good answer by editing the original question.
I have no idea what you are asking in your new question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.