GJ Guo
GJ Guo

Reputation: 11

Why can't I draw a picture in canvas?

I tried to put a picture in the canvas, but it just doesn't appear. I've Googled it to find out what's wrong, unfortunately I still can't solve it.

Here's my code:

window.onload = function() {
  var cnvs = document.getElementById("gc");
  var ctx = cnvs.getContext("2d");
  var img = new Image();
  img.src = "/img/road.jpg";
  ctx.drawImage(img, 0, 0);
};
* {
  box-sizing: border-box;
  padding: 0;
  margin: 0;
}

.game-border {
  display: flex;
  justify-content: center;
  justify-items: center;
}

#gc {
  width: 100vmin;
  height: 100vmin;
  background-color: coral;
}
<div class="game-border">
  <canvas id="gc"></canvas>
</div>

Upvotes: 1

Views: 48

Answers (1)

nkl
nkl

Reputation: 38

If you try to call drawImage() before the image has finished loading, it won't do anything. So you need to be sure to use the load event so you don't try this before the image has loaded:

var img = new Image();   // Create new img element
img.addEventListener('load', function() {
  // execute drawImage statements here
  ctx.drawImage(img,0,0);
}, false);
img.src = 'myImage.png'; // Set source path

Source: https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Using_images

Upvotes: 1

Related Questions