使用Javascript刷新多个图像

问题描述 投票:0回答:3

我已经构建了一个页面,可以从我们使用办公室监控道路网络的各种网络摄像头中提取多个图像。

我们希望图像每30秒自动更新一次,我的JavaScript不是很棒我害怕。

我知道我可以轻松刷新整个页面,我也可以刷新单个图像。但是来自不同URL的多个图像证明更加困难。

相机图像是页面上唯一的图像,如果它有用,并以HTML格式显示如下:

<figure class="fluid tiles">
<img src="cam/17002.php" alt="M" onerror="this.src = 'camoffline.png';" />
<figcaption class="textStyle">M20 00/1A J10-11<br /><small>Camera: 17002</small></figcaption>
</figure>
javascript html image
3个回答
0
投票

// get all of the images from the page
const images = document.getElementsByTagName( 'img' );

// perform this function every 30,000 ms (30 sec)
const timer = setInterval( function(){
  // go through each image and reference a custom attribute
  // 'data-source' to preserve the original image's src
  for( var i=0, x=images.length; i<x; i++ ){
    // select each image, individually
    let image = images[i];
    let source = image.getAttribute( 'data-source' );
    // if 'data-source' does not exist, create it
    if( !source ){
      source = image.src;
      image.setAttribute( 'data-source', source );
      // give 'data-source' the original image path
    }
    // Add a timestamp to the image source to help mitigate 
    // browser caching
    image.src = source + '?t=' + Date.now();
  }
}, 30000 );
img{ height: 150px; }
<img src="https://image.shutterstock.com/z/stock-photo--week-old-cocker-spaniel-puppy-630877553.jpg">

<img src="https://image.shutterstock.com/z/stock-photo--week-old-cocker-spaniel-puppy-630877553.jpg">

<img src="https://image.shutterstock.com/z/stock-photo--week-old-cocker-spaniel-puppy-630877553.jpg">

<img src="https://image.shutterstock.com/z/stock-photo--week-old-cocker-spaniel-puppy-630877553.jpg">

<img src="https://image.shutterstock.com/z/stock-photo--week-old-cocker-spaniel-puppy-630877553.jpg">

使用.getElementsByTagName('img')收集页面上存在的所有图像。

然后,在一个间隔(setInterval:将继续执行每个### miliseconds的代码)中创建一个for循环,它将遍历用.getElementsByTagName()捕获的HTML集合。

一个想法是在页面上的每个图像上创建一个新属性,“数据源”(数据属性可以是任何东西)。 'data-source'将保留图像文件路径的原始信息。

然后,使用原始图像路径中的值,将该图像路径值重新分配给图像,但添加时间戳作为查询参数。这是为了帮助浏览器加载新图像(浏览器的爱缓存内容,他们可以在哪里)。浏览器看到image.jpeg?t = 1234并认为它是一个与image.jpeg不同的图像?t = 1233


0
投票

我想提出一个使用<canvas>的略微修改的解决方案。这将在固定宽度的容器中绘制所有源,如果它们处于脱机状态,则绘制源应该位于的“脱机”文本。

单击复选框以测试脱机功能。

const sources = [
  "https://cdn.sstatic.net/Sites/stackoverflow/img/sprites.svg",
  "https://cdn.sstatic.net/Sites/stackoverflow/img/sprites.svg"
];

function getSources(offline = false) {
  return !offline ?
    sources.map(src => `${src}?cb=${Date.now()}`) :
    sources.map(() => "");
}

function loadImage(src) {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.addEventListener("load", () => resolve(img));
    img.addEventListener("error", () => reject(`Problem loading ${src}`));
    img.src = src;
  })
}

const offlineCheckbox = document.getElementsByTagName("input")[0],
  canvas = document.getElementsByTagName("canvas")[0],
  ctx = canvas.getContext("2d");

const {
  width,
  height
} = canvas;

function refresh() {
  console.log("Updating");
  getSources(offlineCheckbox.checked).forEach((source, idx, arr) => {
    const w = width / arr.length,
      dx = w * idx,
      dWidth = w * (idx + 1);

    loadImage(source)
      .then(img => {
        ctx.clearRect(dx, 0, dWidth, height);
        ctx.drawImage(img, dx, 0, dWidth, height);
      })
      .catch(err => {
        ctx.clearRect(dx, 0, dWidth, height);
        ctx.strokeText("Offline", dx, height * 0.5, dWidth);
      })
  });

  setTimeout(() => refresh(), 3 * 1000);
}

refresh();
<main>
  <div>
    <label><input type="checkbox"> Pretend to be offline</label>
  </div>
  <div>
    <canvas width="400" height="400"></canvas>
  </div>
</main>

-2
投票

您可以使用timer每30秒重置图像的src

var img = document.querySelector("img.cam");
setInterval(function(){
  // I'm appending # and a date to ensure we don't use a cached version of the file
  img.src = "https://picsum.photos/200/300/?random#" + new Date() ;
}, 2000); // number is in milliseconds
img  { width: 100px; }
<figure class="fluid tiles">
<img class="cam" src="cam/17002.php" alt="M" onerror="this.src='camoffline.png';" />
<figcaption class="textStyle">M20 00/1A J10-11<br /><small>Camera: 17002</small></figcaption>
</figure>
© www.soinside.com 2019 - 2024. All rights reserved.