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
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.