如何获取要在画布中显示的远程图像? [英] How to fetch a remote image to display in a canvas?

查看:157
本文介绍了如何获取要在画布中显示的远程图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从服务器获取图片?

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,我想继续从服务器获取图像。 p>

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


推荐答案

使用内置< a href =http://www.w3schools.com/htmldom/dom_obj_image.asp =nofollow noreferrer> 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屋!

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