为什么我的图像没有显示在画布上? [英] Why is my image not showing on the canvas?

查看:81
本文介绍了为什么我的图像没有显示在画布上?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在左上角的画布上显示图像,并且绘制功能无法正常工作.我做错了什么.

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.

尝试以下方法:

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

这篇关于为什么我的图像没有显示在画布上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆