簡體   English   中英

使用Javascript刷新多個圖像

[英]refresh multiple images using Javascript

我建立了一個頁面,可以從使用辦公室監控道路網絡的各種網絡攝像頭中提取多個圖像。

我們希望圖像每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>

 // 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:將繼續每###毫秒執行一次的代碼)中創建一個for循環,該循環將循環遍歷使用.getElementsByTagName()捕獲的HTML集合。

一種想法是在頁面上的每個圖像上創建一個新屬性,即“數據源”(數據屬性實際上可以是任何東西)。 “數據源”將保留圖像文件路徑的原始信息。

然后,使用原始圖像路徑中的值,將該圖像路徑值重新分配給圖像,但添加時間戳作為查詢參數。 這是為了幫助瀏覽器加載新圖像(瀏覽器的愛緩存內容,如果可以的話)。 瀏覽器看到image.jpeg?t = 1234並認為它是與image.jpeg?t = 1233不同的圖像

我想提出一個使用<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> 

您可以使用計時器每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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM