debugoz debugoz - 2 years ago 130
Javascript Question

HTML Canvas not displaying image

Im sure this has got to be something simple that I am overlooking, but I can't seem to get my canvas to display an jpg stored on the server.

<img id="test_img" alt="test" src="/media/tmp/a4c1117e-c310-4b39-98cc-43e1feb64216.jpg"/>
<canvas id="user_photo" style="position:relative;"></canvas>
<script type="text/javascript">
var image = new Image();
image.src = "/media/tmp/a4c1117e-c310-4b39-98cc-43e1feb64216.jpg";
var pic = document.getElementById("user_photo");
pic.getContext('2d').drawImage(image, 0, 0);

displays as expected, however the canvas is blank, though it does seem to have the correct dimensions. Any one see what I'm doing wrong?

My tired eyes will appreciate any help.


Answer Source

you may want to use the following approach

image.onload = function() {
    pic.getContext('2d').drawImage(image, 0,0);

so you ensure that the image is loaded when trying to draw it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download