10

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

Ashley Strout
  • 6,107
  • 5
  • 25
  • 45
debugoz
  • 143
  • 1
  • 1
  • 5

3 Answers3

14

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.

Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
pollirrata
  • 5,188
  • 2
  • 32
  • 50
3
var initialFloorplanWidth = 0;
var initialFloorplanHeight = 0;
var canvasImage = new Image();
documentReady = function () {
    preloadFloorplan();
}
preloadFloorplan = function () {
    onLoad = function () {
        initialFloorplanHeight = canvasImage.height;
        initialFloorplanWidth = canvasImage.width;
        var canvasHtml = '<canvas id="MainCanvas" width="' + initialFloorplanWidth + '" height="' + initialFloorplanHeight + '">Canevas non supportés</canvas>';
        $("#MainContainer").append(canvasHtml);
        var canvas = $("#MainCanvas")[0];
        var canvasContext = canvas.getContext("2d");
        canvasContext.drawImage(canvasImage, 0, 0);
    }
    canvasImage.onload = onLoad;
    canvasImage.src = initialFloorplan;
}

This code works well.

-1

Try doing that when the document is loaded. I have a feeling your code is running before the image is available. You can also detect when the img itself is loaded. See this.

Community
  • 1
  • 1
hvgotcodes
  • 118,147
  • 33
  • 203
  • 236
  • Thanks you sir, add the code to the image load function works a treat. One question though, presumable I don't need the `` to load the pic into the canvas, would putting the canvas code in the $(document).ready function achieve the same thing? – debugoz May 15 '12 at 01:33