HTML canvas not displaying image

I am sure that this should be something simple that I am missing, but I cannot make my canvas display 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>

<img>displayed as expected, however the canvas is empty, although it seems to have the correct dimensions. Does anyone see what I'm doing wrong?

My tired eyes will appreciate any help.

thank

+5
source share
4 answers

you can use the following approach

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

to ensure that the image loads when you try to draw it.

+3
source
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.

+2
source

, . , , . , img. . .

0

Perhaps this has something to do with the rest of your code. Is "user_photo" identified in code?

0
source

All Articles