24 October, 2016

on Leave a Comment

Display continously changing image in broswer without being cached

Recently. I got a requirement where job was to display a image from a folder. But the challenge was that image will be changing continuously and the display should also sync with that.  I tried many things but often the problem was same , image was getting cached and it was displaying the same image. On doing some search on web , stackoverflow suggested that I need to a random variable to the image name so that it wont get cached and the best way was to add combination on date and time.  And it worked!

Here is the full solution using HTML5 canvas:

// canvas to display image in your maine HTML body
<canvas id="x" style="width:-moz-available;height:width:-moz-available;display:none;"/></canvas>

//Then paste this javascript
<script type="text/JavaScript">

var url = 'img/a.jpg';                      // url to load image from
var refreshInterval = 1000;          // time in which image will be refreshed (time is in millisecond)
var drawDate = true;                   //draw date string
var img;

// setting canvas properties

var canvas = document.getElementById("x");
var context = canvas.getContext("2d");

img = new Image();
img.onload = function() {
var imgWidth = img.width;
var imgHeight = img.height;
 context.canvas.width = imgWidth;
 context.canvas.height = imgHeight;
 context.drawImage(img, 0, 0, imgWidth, imgHeight);

function refresh()         // function which adds the random value and refreshes continously
    img.src = url + "?t=" + new Date().getTime();



Landing Page eBook WP Shopping Cart

Follow me