如何在同一页面上两次使用基于ID的html5画布

时间:2019-03-25 13:41:10

标签: javascript canvas html5-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>

1 个答案:

答案 0 :(得分:0)

使用getElementsByClassName。然后,您将获得一个数组。例如类box

canvas = document.getElementsByClassName("box");

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