Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Image drawn to HTML5 Canvas does not display correctly on first load

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();
like image 754
Jarek Avatar asked Dec 01 '11 18:12

Jarek


People also ask

Which built in HTML5 object is used to draw on the canvas?

The HTML <canvas> element is used to draw graphics, on the fly, via JavaScript. The <canvas> element is only a container for graphics. You must use JavaScript to actually draw the graphics. Canvas has several methods for drawing paths, boxes, circles, text, and adding images.

Is HTML5 canvas still used?

The HTML5 canvas has the potential to become a staple of the web, enjoying ubiquitous browser and platform support in addition to widespread webpage support, as nearly 90% of websites have ported to HTML5.


1 Answers

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.

like image 83
Simon Sarris Avatar answered Nov 16 '22 04:11

Simon Sarris