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.

j08691
  • 204,283
  • 31
  • 260
  • 272
Ionut Eugen
  • 481
  • 2
  • 6
  • 27
  • Your image is not loaded yet. – ASDFGerte Aug 07 '18 at 16:13
  • What do u mean ? – Ionut Eugen Aug 07 '18 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 – SPlatten Aug 07 '18 at 16:17
  • Also see e.g. https://stackoverflow.com/questions/29572560/load-image-from-url-and-draw-to-html5-canvas, https://stackoverflow.com/questions/32880641/canvascontext2d-drawimage-issue-onload-and-cors, https://stackoverflow.com/questions/15048279/drawimage-not-working, ... – ASDFGerte Aug 07 '18 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. – ASDFGerte Aug 07 '18 at 16:27

1 Answers1

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>
Helder Sepulveda
  • 15,500
  • 4
  • 29
  • 56