简体   繁体   中英

Why is my image not showing on the canvas?

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>

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";  
}

You should draw image after it is loaded

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

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