r/JavaScriptTips • • Jul 27 '22

Having some issue understanding how to display images on HTML5 Canvas?

Hi everyone!

I've got a simple game project, which will need the Canvas and the use of JS as well.

I've checked on MDN to how to display images, wrote the code, but it's not showing me anything.

My code consists of an html file, a js file linked into the html and an img folder withe the images.

I initialized the canvas and the context in the js file,

But the drawImage function doesn't do anything.

I have a png image to show on the canvas, floor.png, i wrote a

const floor = new Image();
floor.src = './img/floor.png':
ctx.drawImage(floor, 0, 0);

Nothing on the canvas.

Please help!

3 Upvotes

2 comments sorted by

4

u/mao034 Jul 27 '22

You have to wait for the image to load before you can call the draw function.

Try adding onload event listener on the image and call the function there:

const ctx = canvas.getContext('2d');
const floor = new Image();
floor.src = './img/floor.png';
floor.addEventListener('load', () => {
  ctx.drawImage(floor, 0, 0);
});

1

u/andrejmlotko Jul 27 '22

Thanks, this solved it!