Reputation: 1
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 displayed in the canvas. Also, I tried the same code in w3schools browser somewhere else, but still it's not working in that browser either.
<!DOCTYPE html>
<html>
<body>
<p>Image to use:</p>
<img id="scream" src="flower.jpg" alt="The Scream" width="220" height="277"><p>Canvas:</p>
<canvas id="myCanvas" width="250" height="300" style="border:1px solid #d3d3d3;">
<script>
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var img=document.getElementById("scream");
ctx.drawImage(img,10,10);
</script>
</body>
</html>
Upvotes: 0
Views: 644
Reputation: 2878
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:
<script>
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var img=document.getElementById("scream");
img.onload = function(){
ctx.drawImage(img,10,10);
}
</script>
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.
Upvotes: 1
Reputation: 3717
You probably need to run the javascript on load, rather than directly in body. Change you javascript into this and it should work (at least it does in this fiddle):
function setup_canvas() {
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var img=document.getElementById("scream");
ctx.drawImage(img,10,10);
}
window.onload = setup_canvas;
Also, as described in this thread explicitly setting window.onload
is not a very good practice, as it might be overwritten by subsequent scripts, so for anything other than testing you would want to use a framework or addEventListener
/attachEvent
.
Upvotes: 0
Reputation: 472
I would use the image directly, instead of taking it out of the <img>
-tag
var c = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
var imageObj = new Image();
imageObj.onload = function() {
ctx.drawImage(imageObj, 10, 10);
};
imageObj.src = 'flower.jpg';
Upvotes: 1