views:

2860

answers:

4

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"&gt;
    <img src="http://l.yimg.com/a/i/ww/beta/y3.gif"&gt;
    <img src="http://static.ak.fbcdn.net/images/welcome/welcome_page_map.png"&gt;
  </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);
}
+7  A: 

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';
spoon16
It's worth noting that you can't synchronously request a resource, so you should actually do something along the lines of myimage.onload = function() { ctx.drawImage(myimage, x, y); } myimage.src = 'http://myserver/nextimage.cgi';
olliej
+2  A: 

To add an image in JavaScript you can do the following:

myimage = new Image()
myimage.src='http://....'

If an image on your page has an ID "image1", you can assign the src of image1 to myimage.src.

Diodeus
You owe me a coke ;)
spoon16
+1  A: 

If you are using jQuery you can do:

$.('<img src="http://myserver/nextimage.cgi" />).appendTo('#canv');

You can also add widths and anything else in the img tag.

Darryl Hein
Canvas doesn't display child elements, it's a programmable bitmap context you can draw to with JS, one of the API functions is drawImage() which takes an Image element/object and draws it into the buffer. It allows you to do nifty things that were previously not possible eg. http://canvaspaint.org/
olliej
Now that I understand the question, I would give a different answer. :)
Darryl Hein
+2  A: 

If you want to draw an image to a canvas you also need to wait for the image to actually load, so the correct thing to do will be:

myimage = new Image();
myimage.onload = function() {
    context.drawImage(myimage, ...);
}
myimage.src = 'http://myserver/nextimage.cgi';
olliej