Why is my image not showing on the canvas?

风格不统一 提交于 2019-12-25 07:06:40

问题


I am trying to show an image on a canvas at the top corner and the draw function is not working properly. What have I done wrong.

The above image is what I want to show on the screen.

<html>
<head>
<title></title>
</head>

<body>
<p><canvas id="canvas" style="border:1px solid black;" width="450" height="310"></canvas>
</body>


<script>
    var c=document.getElementById("canvas");
    var ctx=c.getContext("2d");


    draw();

    function draw(){  
        var img = new Image(); 
        img.src = "t.gif";  
        ctx.drawImage(img,0,0);  
    }
</script>

</html>

回答1:


The problem is that you attempt to draw the image immediately, before the browser has finished downloading it.

Try this instead:

function draw(){  
    var img = new Image();
    img.onload = function() {
        ctx.drawImage(img,0,0);
    };
    img.src = "t.gif";  
}



回答2:


You should draw image after it is loaded

img.onload = function() {
    // here...
};


来源:https://stackoverflow.com/questions/25705121/why-is-my-image-not-showing-on-the-canvas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!