I'm unable to get image in canvas in html5, what to do?

后端 未结 3 986
遇见更好的自我
遇见更好的自我 2020-12-22 06:08

I have checked this code from my w3schools where its working well.

But when I run this code in my browser, it\'s not working.

The image does not get displaye

3条回答
  •  南方客
    南方客 (楼主)
    2020-12-22 06:29

    The problem is that load of an image is asynchronous, so your Javascript code might run before the image finish his loading. Because of that when ctx.drawImage(img, 10, 10) is called img have no complete data and draws nothing on canvas.

    To solve that you need to wait the image to completely load. Javascript give you the ability to setup a function to run when an image is completely loaded.

    All code that depends of the image data should be put inside the onload callback.

    img.onload = function(){ 
        ctx.drawImage(img,10,10);
    }
    

    Your script with the modified parts:

    
    

    If the src is correct doesn't matter if the image is loaded from a html tag or created dynamically in Javascript with new Image(), the onload method works for both.

提交回复
热议问题