Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
}
like image 964
Mark Harrison Avatar asked Oct 02 '08 19:10

Mark Harrison


1 Answers

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';
like image 55
Eric Schoonover Avatar answered Oct 10 '22 17:10

Eric Schoonover