js给页面添加随机像素噪声背景

js给页面添加随机像素噪声背景_第1张图片

WIDTHHEIGHT可以取小一点,但是取太小很不好看,因为生成的噪声看起来不随机了,小片区域就有重复。创建一个canvas但不放页面。这个canvas只用来生成图片,然后循环遍历在canvas里面画1px的矩形,toDataURL自动就转换base64了。如果想要更浅的噪声只要随机数的产生范围。

DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>背景噪声让网页更有质感title>
    <style>
        body {
            margin: 0;
            padding: 0;
            height: 100vh;
        }
    style>
head>

<body>
body>
<script>
    const WIDTH = 256;
    const HEIGHT = 256;
    var dom = document.createElement('canvas');
    dom.width = WIDTH;
    dom.height = HEIGHT;
    var ctx = dom.getContext("2" + "d");  // 不能直接写2d部分浏览器会解析出奇怪的东西
    for (let y = 0; y < HEIGHT; y++) {
        for (let x = 0; x < WIDTH; x++) {
            var color = Math.floor(Math.random() * 12 + (255 - 16)).toString(16);
            ctx.fillStyle = `#${color}${color}${color}`;
            ctx.fillRect(x, y, 1, 1);
        }
    }
    var url = dom.toDataURL(`image/png`, 0.6)
    document.body.style += ';background-image:url(' + url + ');';
script>

html>

或者更通用的:

DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>背景噪声让网页更有质感title>
    <style>
        body {
            margin: 0;
            padding: 0;
            height: 100vh;
            position: relative;
            background-position: -100%; /* 这样body本身没背景了 */
            background-repeat: no-repeat;
        }

        body::before {
            content: "";
            position: absolute;
            background-image: inherit;
            left: 0;
            top: 0;
            right: 0;
            bottom: 0;
            background-repeat: repeat;
            opacity: .1; /* 然后直接用透明度 */
        }
    style>
head>

<body>
body>
<script>
    const WIDTH = 256;
    const HEIGHT = 256;
    var dom = document.createElement('canvas');
    dom.width = WIDTH;
    dom.height = HEIGHT;
    var ctx = dom.getContext("2" + "d");
    for (let y = 0; y < HEIGHT; y++) {
        for (let x = 0; x < WIDTH; x++) {
            var color = Math.floor(Math.random() * 255).toString(16);
            ctx.fillStyle = '#'.concat(color, color, color);
            ctx.fillRect(x, y, 1, 1);
        }
    }
    var url = dom.toDataURL(`image/png`, 0.6)
    document.body.style += ';background-image:url(' + url + ');';
script>

html>

你可能感兴趣的:(前端,javascript,前端,html)