1


I am trying to show an image on my page from a different url.

<body>
<div id="container">
    <br />

    <canvas width="500px" height="375px" id="canvas">
    </canvas>
    <img src="http://yinoneliraz-001-site1.smarterasp.net/MyPicture.png" />

</div>
<script>

    var img = new Image;
    img.src = "http://yinoneliraz-001-site1.smarterasp.net/MyPicture.png";

    var timer = setInterval(function () { MyTimer() }, 200);
    function MyTimer() {
        var ctx = canvas.getContext('2d');
        ctx.drawImage(img, 0, 0,500,675);
        img = new Image;
        img.src = "http://yinoneliraz-001-site1.smarterasp.net/MyPicture.png";
    }
</script>

The image on the other site is being saved every 1.5 seconds.
The result is that I cant view the image.
Any ideas why?

Thanks!

Yinon Eliraz
  • 317
  • 1
  • 6
  • 22
  • Could be an issue with the image cacheing, or your server/client connection speed is not fast enough to download the image before it is deleted and rewritten. – Mark Aug 24 '13 at 10:49

2 Answers2

5

1. Cache issue

Your MyPicture.png returns Cache-Control: max-age=31536000 in HTTP response. So browser may get image from its cache on second time. You need to add query string something like thie:

img.src = "http://yinoneliraz-001-site1.smarterasp.net/MyPicture.png?time=" + (new Date()).getTime();

2. Too short fetching period.

I think fetching period 200msec is too short. It's better to bind onload event handler to the image object. See How to fetch a remote image to display in a canvas?.

function copyCanvas(img) {
    var canvas = document.getElementById('canvas');
    var ctx = canvas.getContext('2d');
    ctx.drawImage(img, 0, 0);
}

function loadImage() {
    var img = new Image();
    img.onload = function () {
        copyCanvas(img);
    };
    img.src = "http://yinoneliraz-001-site1.smarterasp.net/MyPicture.png?time=" + (new Date()).getTime();
}

3. Double buffering

I think your script intend to pre-load image. So it's better to make a double buffering.

Single Buffering version: http://jsfiddle.net/tokkonoPapa/dSJmy/1/

Double Buffering version: http://jsfiddle.net/tokkonoPapa/dSJmy/2/

Community
  • 1
  • 1
tokkonopapa
  • 167
  • 4
0

You have not defined canvas. Define it first with:

var canvas = document.getElementById('canvas');

Then, use load event to draw image on to the canvas.

Checkout the fiddle, LoadImgURL which demonstrates the whole process.