Categories
canvas html image refresh

How to display a constantly changing image file in a browser without refresh flicker?

I’m displaying an image (from a file) on the browser using html… I have another program that keeps taking a screenshot of my screen and storing it as an image file “https://www.faqcode4u.com/faq/411828/image.jpeg”. I am displaying this image on the browser periodically using setTimeout. However the image is not changing on the browser..

Here is my code… I have used an Image object so that a new image is loaded everytime the javascript function runs, however that does not seem to be working…

<html>
<head>
<script type="text/JavaScript">
var x=0, y=0;
var canvas, context, img;
function timedRefresh(timeoutPeriod)
{
canvas = document.getElementById("x");
context = canvas.getContext("2d");
img = new Image();
img.src = "https://www.faqcode4u.com/faq/411828/image.jpeg";
context.drawImage(img, x, y);
x+=20; y+=20;
//img.destroy();
setTimeout("timedRefresh(1000)",timeoutPeriod);
}
</script>
<title>JavaScript Refresh Example</title>
</head>
<body onload="JavaScript:timedRefresh(1000);">
<canvas id="x" width="600" height="600" />
</body>
</html>

First, when you set the src attribute of your image object, the image has not been loaded yet, you need to refresh your canvas when the onload of the image gets fired (when the image is done loading).

Secondly, the browser tries to use the cached image image.jpeg. To avoid that, add a bogus argument to the image URI.

For example :

var timeoutPeriod = 1000;
var imageURI = "https://www.faqcode4u.com/faq/411828/image.jpeg";
var x=0, y=0;
var img = new Image();
img.onload = function() {
var canvas = document.getElementById("x");
var context = canvas.getContext("2d");
context.drawImage(img, x, y);
x+=20; y+=20;
setTimeout(timedRefresh,timeoutPeriod);
};
function timedRefresh() {
// just change src attribute, will always trigger the onload callback
img.src = imageURI + '?d=' + Date.now();
}

And then it should work.