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();
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With