2

I want just to draw an image on canva using drawImage() method .But it happen sometime that the image is not drawn . even when I use the onload event it still fail to display the image. Before I ask my question I want just to precise that the image is drawn somtimes and not drawn sometime .So what is the reason of the this problem and how can I tackle or fix it .

let imagez = new Image();
    imagez.src="photo/run.png";
    context.drawImage(imagez,10,10,50,60); // it does not draw the image always. why?

I expect the image to be drawn whenever I  refresh the page
GNETO DOMINIQUE
  • 628
  • 10
  • 19

3 Answers3

1

That most likely happens because the drawImage() method is called before the actual image is completely loaded. Wait for it to finish loading before you call drawImage().

var canvas = document.createElement("canvas");
document.body.appendChild(canvas);
canvas.width = 400;
canvas.height = 300;
var context = canvas.getContext("2d");
let imagez = new Image();
imagez.onload = function() {
  context.drawImage(imagez, 10, 10, 50, 60);
}
imagez.src = "https://picsum.photos/400/300";
obscure
  • 11,916
  • 2
  • 17
  • 36
0

For this you have to wait for the image(s) to load into memory before they are available to draw to the canvas.

A simple loadIMAGE() function to achieve this might look something like this...

function loadIMAGE(path, x, y, w, h) {
    var img = new Image();

    img.addEventListener("load", function(e) {
        // 'this' === the image Object
        context.drawImage(this, x, y, w, h); 
    }, !1);

    img.src = path;
}

// USAGE
loadIMAGE("photo/run.png", 10, 10, 50, 60);

It is important that the event-Handling function is defined before the src value is assigned.

Hope that helped :)

Brian Peacock
  • 1,801
  • 16
  • 24
0

You are attempting to draw the image without knowing if it was successfully loaded...
Here is a working sample, using the onload event

const canvas = document.getElementById("gameArea");
context = canvas.getContext("2d");

let imagez = new Image();
imagez.onload = function () {
  context.drawImage(imagez, 10, 10, 50, 60); 
}
imagez.src = "https://upload.wikimedia.org/wikipedia/commons/e/e2/3D_Gyroscope.png";
<canvas id=gameArea></canvas>
Helder Sepulveda
  • 15,500
  • 4
  • 29
  • 56