Reload <img> element from same source

I have an image at the URL http://192.168.1.53/html/cam.jpg (from a Raspberry Pi) and this image is changing very fast (it is from a camera).

So I want to have some JavaScript on a website that will reload this image every second for example.

My HTML is:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Pi Viewer</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
  </head>
  <body>

      <style>
          img,body {
              padding: 0px;
              margin: 0px;
          }
      </style>

      <img id="img" src="http://192.168.1.53/html/cam.jpg">
      <img id="img1" src="http://192.168.1.53/html/cam.jpg">

      <script src="script.js"></script>
  </body>
</html>

And my script:

function update() {
    window.alert("aa");
    document.getElementById("img").src = "http://192.168.1.53/html/cam.jpg";
    document.getElementById("img1").src = "http://192.168.1.53/html/cam.jpg";
    setTimeout(update, 1000);
}
setTimeout(update, 1000);

alert is working, but the image is not changing :/ (I have 2 images (they are the same))

Answers:

Answer

The problem is that the image src is not altered so the image is not reloaded.

You need to convince the browser that the image is new. A good trick is to append a timestamp to the url so that it is always considered new.

function update() {
    var source = 'http://192.168.1.53/html/cam.jpg',
        timestamp = (new Date()).getTime(),
        newUrl = source + '?_=' + timestamp;
    document.getElementById("img").src = newUrl;
    document.getElementById("img1").src =  newUrl;
    setTimeout(update, 1000);
}

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.