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);
}
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';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With