canvas not drawing images

Ponyisasquare picture Ponyisasquare · Sep 27, 2013 · Viewed 10.5k times · Source

I'm just trying to figure out how to get an image to draw on a canvas. I followed a tutorial on W3 schools, but when i tried it on my own it doesn't seem to be working. I copy and paste the code below into an HTML file, and the image never loads into the canvas. I downloaded the picture into the same directory. I've been asking around, and looked online, but no one seems to know what the problem is. I'm 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>

Answer

user1693593 picture user1693593 · Sep 28, 2013

Your image probably hasn't finished loading at the point you are using drawImage:

HTML

Add onload handler in img tag:

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

Then the function to handle it:

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

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

Online demo here

Be aware of that where you place the scripts in your document matters as well.

I would recommend you setting the src attribute in JavaScript as well. That makes it more "safe" to handle the onload (or subscribed event with img.addEventListener('load', ...).