Skip to content Skip to sidebar Skip to footer

Why Is The Image Drawn In The Canvas When Debugging But Not When Running?

I'm learning HTML5 and Javascript and I'm trying to draw an image on a canvas. I have the following code which draws the image if I step through the code after breaking on the line

Solution 1:

You have to wait until the image element is fully loaded by the browser before calling the drawImage method, even if your image element is created from a base64 string and not from an external file. So just make use of the onload event of the image object. A quick fix would be like this:

var img = document.createElement('img');

img.onload = function()
{
    var canvas = document.getElementById('picCanvas');
    canvas.width = this.width;
    canvas.height = this.height;
    var ctx = canvas.getContext('2d');
    ctx.drawImage(this, 0, 0);
}

img.src = e.target.result;

Post a Comment for "Why Is The Image Drawn In The Canvas When Debugging But Not When Running?"