10

I'm following a tutorial on importing and displaying images on an HTML5 canvas. Everything works fine, until I try to change the image itself. For example, I'll have a yellow circle as my image, and the script works fine. But if I open the image itself in Paint and change the circle to red, and refresh the page, the circle won't show up until I click or refresh again a second time manually. Here is the code snippet I'm using:

var topMap = new Image();
topMap.src = "topMap.png";

function drawMap() {
    context.clearRect(0, 0, WIDTH, HEIGHT);
    context.drawImage(topMap, 0, 0);
}

function init() {
    drawMap();
}

init();
Phrogz
  • 296,393
  • 112
  • 651
  • 745
Jarek
  • 145
  • 1
  • 1
  • 9

1 Answers1

19

The circle is probably not showing up because you are drawing it before the image is loaded. Change your last statement to:

// Lets not init until the image is actually done loading
topMap.onload = function() {
  init();
}

The reason it works after you hit refresh is because the image is now pre-loaded into the cache.

You always want to wait for any images to load before you attempt to draw them or nothing will show up on the canvas instead.

Simon Sarris
  • 62,212
  • 13
  • 141
  • 171
  • 6
    More simply, `topMap.onload = drawMap;`. Note that [you should set the `onload` _before_ you set `src`](http://stackoverflow.com/questions/4776670/should-setting-an-image-src-to-dataurl-be-available-immediately). So: `var topMap = new Image; topMap.onload=drawMap; topMap.src="topMap.png";` – Phrogz Dec 01 '11 at 19:19
  • Make sure you heed Phrogz's advice here too! – Simon Sarris Dec 01 '11 at 20:21
  • Yes, here is exactly as I wrote it: `var topMap = new Image(); topMap.onload=init; topMap.src = "topMap.png";` – Jarek Dec 01 '11 at 22:06
  • This totally works... I was having the same problem with an Image. +1! – jRam90 Sep 27 '14 at 20:41