0

So I taught of making something random. Then I wanted o to draw an image so I go documenting online and I come back with a small piece of code that for some reasons won't work.

const cvs = document.getElementById("gameArea"); const ctx = cvs.getContext("2d"); let playArea = new Image(); playArea.src="./Textures/play_area.png"; function draw(){ ctx.drawImage(playArea,0,0); } draw(); 

The image is in the textures folder that is in the same folder as the script.

5
  • Your image is not loaded yet. Commented Aug 7, 2018 at 16:13
  • What do u mean ? Commented Aug 7, 2018 at 16:14
  • JavaScript and the browser content loads asynchronously, what ASDFGerte is getting at, is that the Javascript may be running before the content has finished loading Commented Aug 7, 2018 at 16:17
  • Also see e.g. stackoverflow.com/questions/29572560/…, stackoverflow.com/questions/32880641/…, stackoverflow.com/questions/15048279/drawimage-not-working, ... Commented Aug 7, 2018 at 16:23
  • In that case, make sure the related image is actually in the folder, and check for error messages in the console (not found, CORS, ...). Whatever you do, to have it work reliably (if the image is not in cache and therefore not immediately loaded), you need to use an event listener first. Commented Aug 7, 2018 at 16:27

1 Answer 1

2

You should execute the draw on the window.onload just to prevent it from running before the content is loaded.

Here is an example:

const cvs = document.getElementById("gameArea"); cvs.width = cvs.height = 800; const ctx = cvs.getContext("2d"); let playArea = new Image(); playArea.src="https://upload.wikimedia.org/wikipedia/commons/e/e2/3D_Gyroscope.png"; function draw(){ ctx.drawImage(playArea,0,0); } window.onload = function() { draw(); }
<canvas id=gameArea></canvas>

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.