Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
117 views
in Technique[技术] by (71.8m points)

javascript - 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>

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);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use the built-in JavaScript Image object.

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.

Thanks 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';

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...