A way to create random-noise background image (png) with javascript?

后端 未结 4 1166
Happy的楠姐
Happy的楠姐 2021-02-09 02:31

The new layout of YouTube added a background random-noise which I like very much, having seen almost exactely the same effect on other sites, so I plan to use the same technique

相关标签:
4条回答
  • 2021-02-09 03:06

    To generate image client-side, I suggest you to have a look to HTML5 canvas element.

    You can draw on a canvas with Javascript (even if the canvas element is hidden), and so generate anything you want (including a simple noise tile).

    Resource to learn Canvas drawing : https://developer.mozilla.org/en/Drawing_Graphics_with_Canvas

    After that, you can export your canvas as URL with the method toDataURL (a string like "data:image/png;base64....") which is interpreted by browsers like a traditionnal url for an image, so you can set it as css background for your body element.

    Warning 1 : Canvas is supported by all modern browsers and you can emulate it on IE with ExplorerCanvas - but I don't know if ExplorerCanvas support .toDataURL()

    Warning 2 : Canvas is resolution-dependant, so I suggest you to generate a little tile (32*32, or 64*64) and repeat it

    Edit : An example of tiled background : http://jsfiddle.net/SfzPc/12/

    Edit 2 : An completed example with a noisy background : http://jsfiddle.net/SfzPc/14/

    0 讨论(0)
  • 2021-02-09 03:14

    There are two jQuery plugin libraries that do exactly what you are looking for: NoiseGen and Noisy. Haven't used either yet but they both look pretty good.

    NoiseGen

    • Project: http://primegap.net/2011/10/20/noisegen-generate-background-noise-with-jquery/
    • Demo: http://www.lucaongaro.eu/demos/noisegen/

    Noisy

    • Project: https://github.com/DanielRapp/Noisy
    • Demo: http://rappdaniel.com/other/noisy-sample/
    0 讨论(0)
  • 2021-02-09 03:24

    Fyi: Base64 is binary data represented as a string. Most likely the original image still came out of Photoshop and was later encoded into Base64. This technique helps having less http-requests per page view, as the actual image data can be saved and cached inside the css or html document.

    0 讨论(0)
  • 2021-02-09 03:26

    You can use CSS to display this image:

    #someimageselector {
        background: white url('data:image/png;base64,iVBOR...lots of data') repeat scroll left top;
    }
    

    You can change the initial color of your background by editing the value white.

    To set CSS with JavaScript, set the background property of an element:

    document.getElementByID("someimageselector").background = 'white url(data:image/png....';
    
    0 讨论(0)
提交回复
热议问题