Canvas not painting

I'm just trying to figure out how to get an image for drawing on canvas. I followed the W3 school textbook, but when I tried it on my own, it doesn't seem to work. I copy and paste the code below into an HTML file and the image never loads into the canvas. I uploaded the image to the same directory. I asked and looked online, but no one seems to know what the problem is. I am using an updated version of chrome (version 29.0.1547.76 m).

<!DOCTYPE html>
<html>
<body>

<p>Image to use:</p>
<img id="scream" src="img_the_scream.jpg" alt="The Scream" width="220" height="277">

<p>Canvas:</p>
<canvas id="myCanvas" width="250" height="300" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>

<script>

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var img=document.getElementById("scream");
this.ctx.drawImage(img,10,10);

</script>

</body>
</html>
+4
source share
2 answers

Your image probably did not finish loading where you use drawImage:

HTML

Add onload handler in img tag:

<img id="scream" onload="draw()" src="...

Then the function to process:

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var img=document.getElementById("scream");

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

-

, .

src JavaScript. "" onload ( img.addEventListener('load', ...).

+4

, , :

image.onload = function() {
    pic.getContext('2d').drawImage('your image to display', 0,0);
}
+2

All Articles