簡體   English   中英

如何在同一頁面上使用基於ID兩次的html5畫布

[英]How to use a html5 canvas that is based on ID twice on same page

我正在使用canvas在這里我想在同一頁面上多次使用相同的畫布我嘗試使用類名getElementsByClassName並使用查詢選擇器。 但它不起作用。 任何人都可以指出我在正確的方向可能是什么問題在這里我怎么能實現? 在box1,box2這兩個框中我想添加相同的畫布。

 const noise = () => { let canvas, ctx; let wWidth, wHeight; let noiseData = []; let frame = 0; let loopTimeout; // Create Noise const createNoise = () => { const idata = ctx.createImageData(wWidth, wHeight); const buffer32 = new Uint32Array(idata.data.buffer); const len = buffer32.length; for (let i = 0; i < len; i++) { if (Math.random() < 0.5) { buffer32[i] = 0xff000000; } } noiseData.push(idata); }; // Play Noise const paintNoise = () => { if (frame === 9) { frame = 0; } else { frame++; } ctx.putImageData(noiseData[frame], 0, 0); }; // Loop const loop = () => { paintNoise(frame); loopTimeout = window.setTimeout(() => { window.requestAnimationFrame(loop); }, (1000 / 25)); }; // Setup const setup = () => { wWidth = window.innerWidth; wHeight = window.innerHeight; canvas.width = wWidth; canvas.height = wHeight; for (let i = 0; i < 10; i++) { createNoise(); } loop(); }; // Reset let resizeThrottle; const reset = () => { window.addEventListener('resize', () => { window.clearTimeout(resizeThrottle); resizeThrottle = window.setTimeout(() => { window.clearTimeout(loopTimeout); setup(); }, 200); }, false); }; // Init const init = (() => { canvas = document.getElementById('noise'); //canvas = document.getElementsByClassName('noise'); ctx = canvas.getContext('2d'); setup(); })(); }; noise(); 
 .noise { z-index: 100; position: absolute; top: 0; left: 0; width: 100%; height: 100%; pointer-events: none; opacity: .5; } .box1, .box2 { position: relative; width: 300px; height: 300px; margin: 20px; background: #eee; } 
 <div class="box1"> <canvas id="noise" class="noise"></canvas> </div> <div class="box2"> <canvas id="noise" class="noise"></canvas> </div> 

使用getElementsByClassName 然后你會得到一個數組。 例如對於類box

canvas = document.getElementsByClassName("box");

for (i = 0; i < canvas.length; i++) { //...do smth here...// }

暫無
暫無

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

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