I'm unable to get image in canvas in html5, what to do?

后端 未结 3 985
遇见更好的自我
遇见更好的自我 2020-12-22 06:08

I have checked this code from my w3schools where its working well.

But when I run this code in my browser, it\'s not working.

The image does not get displaye

相关标签:
3条回答
  • 2020-12-22 06:28

    You probably need to run the javascript on load, rather than directly in body. Change you javascript into this and it should work (at least it does in this fiddle):

    function setup_canvas() {
        var c=document.getElementById("myCanvas");
        var ctx=c.getContext("2d");
        var img=document.getElementById("scream");
        ctx.drawImage(img,10,10);
    }
    
    window.onload = setup_canvas;
    

    Also, as described in this thread explicitly setting window.onload is not a very good practice, as it might be overwritten by subsequent scripts, so for anything other than testing you would want to use a framework or addEventListener/attachEvent.

    0 讨论(0)
  • 2020-12-22 06:29

    The problem is that load of an image is asynchronous, so your Javascript code might run before the image finish his loading. Because of that when ctx.drawImage(img, 10, 10) is called img have no complete data and draws nothing on canvas.

    To solve that you need to wait the image to completely load. Javascript give you the ability to setup a function to run when an image is completely loaded.

    All code that depends of the image data should be put inside the onload callback.

    img.onload = function(){ 
        ctx.drawImage(img,10,10);
    }
    

    Your script with the modified parts:

    <script>
        var c=document.getElementById("myCanvas");
        var ctx=c.getContext("2d");
        var img=document.getElementById("scream");
        img.onload = function(){ 
            ctx.drawImage(img,10,10);
        }
    </script>
    

    If the src is correct doesn't matter if the image is loaded from a html tag or created dynamically in Javascript with new Image(), the onload method works for both.

    0 讨论(0)
  • 2020-12-22 06:45

    I would use the image directly, instead of taking it out of the <img>-tag

    var c = document.getElementById('myCanvas');
    var ctx = canvas.getContext('2d');
    var imageObj = new Image();
    
    imageObj.onload = function() {
          ctx.drawImage(imageObj, 10, 10);
    };
    imageObj.src = 'flower.jpg';
    
    0 讨论(0)
提交回复
热议问题