简体   繁体   中英

Im having an issue displaying a image from a URL in HTML Canvas

As far as I can see my code is exactly like the code on W3schools except im making a new image instead of using one already in the html, but i cant get it to display anything

<body>
<center><canvas id="myCanvas" width="1000" height="750"></canvas></center>
<script>
    function newImage(src, width, height) {
            var img = document.createElement("img");
            img.src = src;
            img.width = width;
            img.height = height;
            return img;
        }   

    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    var i = newImage("http://i.imgur.com/ELsS4mN.jpg", 1000, 750);
    ctx.drawImage(i,0,0);
</script>

The problem appears because you return image object before it is fully downloaded. Because of that canvas fails to render image data as background image.

You should make use of onload callback function and drawImage only when image data is completely available. This should work:

function newImage(src, width, height, callback) {
    var img = new Image();
    img.width = width;
    img.height = height;
    img.onload = function () {
        callback(img);
    };
    img.src = src;
}

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

newImage("http://i.imgur.com/ELsS4mN.jpg", 1000, 750, function(image) {
    ctx.drawImage(image, 0, 0);
});

Note how instead of returning image from newImage function, you pass callback function in it and invoke it once download complete.

  function newImage(src, width, height, callback) { var img = new Image(); img.width = width; img.height = height; img.onload = function () { callback(img); }; img.src = src; } var c = document.getElementById("myCanvas"), ctx = c.getContext("2d"); newImage("http://i.imgur.com/ELsS4mN.jpg", 1000, 750, function(image) { ctx.drawImage(image, 0, 0); }); 
 <canvas id="myCanvas" width="1000" height="750"></canvas> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM