Why is the image drawn in the canvas when debugging but not when running?

后端 未结 1 811
醉酒成梦
醉酒成梦 2021-01-24 02:44

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

相关标签:
1条回答
  • 2021-01-24 03:15

    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;
    
    0 讨论(0)
提交回复
热议问题