debugoz debugoz - 6 months ago 30
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);
</script>


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

Thanks

Answer

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.