[英]canvas, drawImage does not work for remote picture
I want to draw a picture from web, so I have the following html5 code, that's the example from W3C Shool, but when I load the html page in Chrome, the image was displayed.我想从网络上画一张图片,所以我有以下 html5 代码,这是 W3C Shool 的示例,但是当我在 Chrome 中加载 html 页面时,显示了图像。
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="500" height="500" style="border:1px solid #c3c3c3;">
Your browser does not support the canvas element.
</canvas>
<script type="text/javascript">
var c=document.getElementById("myCanvas");
var cxt=c.getContext("2d");
var img=new Image();
img.src='http://www.w3school.com.cn/i/ct_html5_canvas_image.gif';
cxt.drawImage(img, 0, 0);
</script>
</body>
</html>
The image is from w3school, I can view it in my Chrome, my Chrome is the latest version, so I don't know where the problem is, I even try to download the picture to my local machine and place it in the same directory of the html page above, change the code to img.src='flower.gif', but it still not working.图片来自w3school,可以在我的Chrome中查看,我的Chrome是最新版本,所以不知道问题出在哪里,我什至尝试将图片下载到我的本地机器并将其放在同一目录中在上面的html页面中,将代码更改为img.src='flower.gif',但它仍然不起作用。
The problem is that you are trying to draw the image before it has been loaded.问题是您试图在加载图像之前绘制图像。 Try something like this:尝试这样的事情:
<canvas id="myCanvas" width="500" height="500" style="border:1px solid #c3c3c3;">
Your browser does not support the canvas element.
</canvas>
<script type="text/javascript">
var c = document.getElementById("myCanvas");
var cxt = c.getContext("2d");
var img=new Image();
img.src='http://www.w3school.com.cn/i/ct_html5_canvas_image.gif';
img.onload = draw;
function draw(){
cxt.drawImage(img, 0, 0);
}
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.