如何获取远程图像以显示在画布中? [英] How to fetch a remote image to display in a canvas?
本文介绍了如何获取远程图像以显示在画布中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何从服务器获取图像?
How can I fetch images from a server?
我有这段代码可以让我在画布上绘制一些图像.
I've got this bit of code which allows me to draw some images on a canvas.
<html>
<head>
<script type="text/javascript">
function draw(){
var canvas = document.getElementById('canv');
var ctx = canvas.getContext('2d');
for (i=0;i<document.images.length;i++){
ctx.drawImage(document.images[i],i*150,i*130);
}
}
</script>
</head>
<body onload="draw();">
<canvas id="canv" width="1024" height="1024"></canvas>
<img src="http://www.google.com/intl/en_ALL/images/logo.gif">
<img src="http://l.yimg.com/a/i/ww/beta/y3.gif">
<img src="http://static.ak.fbcdn.net/images/welcome/welcome_page_map.png">
</body>
</html>
不是循环遍历 document.images,我想不断地从服务器获取图像.
Instead of looping over document.images, i would like to continually fetch images from a server.
for (;;) {
/* how to fetch myimage??? */
myimage = fetch???('http://myserver/nextimage.cgi');
ctx.drawImage(myimage, x, y);
}
推荐答案
使用内置的 JavaScript图像对象.
这是使用 Image 对象的一个非常简单的示例:
Here is a very simple example of using the Image object:
myimage = new Image();
myimage.src = 'http://myserver/nextimage.cgi';
这里是对此答案的评论中更适合您的场景的机制.
Here is a more appropriate mechanism for your scenario from the comments on this answer.
谢谢olliej!
值得注意的是,您不能同步请求资源,因此您实际上应该按照以下方式做一些事情:
It's worth noting that you can't synchronously request a resource, so you should actually do something along the lines of:
myimage = new Image();
myimage.onload = function() {
ctx.drawImage(myimage, x, y);
}
myimage.src = 'http://myserver/nextimage.cgi';
这篇关于如何获取远程图像以显示在画布中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文