Animating canvas to look like tv noise

前端 未结 7 2141
野趣味
野趣味 2020-12-22 17:22

I have a function named generateNoise() which creates a canvas element and paints random RGBA values to it; which, gives the appearance of noise.


<
7条回答
  •  青春惊慌失措
    2020-12-22 18:04

    Ken's answer looked pretty good, but after looking at some videos of real TV static, I had some ideas and here's what I came up with (two versions):

    http://jsfiddle.net/2bzqs/

    http://jsfiddle.net/EnQKm/

    Summary of changes:

    • Instead of every pixel being independently assigned a color, a run of multiple pixels will get a single color, so you get these short, variable-sized horizontal lines.
    • I apply a gamma curve (with the Math.pow) to bias the color toward black a little.
    • I don't apply the gamma in a "band" area to simulate the banding.

    Here's the main part of the code:

    var w = ctx.canvas.width,
        h = ctx.canvas.height,
        idata = ctx.createImageData(w, h),
        buffer32 = new Uint32Array(idata.data.buffer),
        len = buffer32.length,
        run = 0,
        color = 0,
        m = Math.random() * 6 + 4,
        band = Math.random() * 256 * 256,
        p = 0,
        i = 0;
    
    for (; i < len;) {
        if (run < 0) {
            run = m * Math.random();
            p = Math.pow(Math.random(), 0.4);
            if (i > band && i < band + 48 * 256) {
                p = Math.random();
            }
            color = (255 * p) << 24;
        }
        run -= 1;
        buffer32[i++] = color;
    }
    

提交回复
热议问题