js 生成随机炫彩背景

时间:2023-03-09 05:36:32
js 生成随机炫彩背景

在浏览 https://ghost.org/xxxx/ 时。

可以使用 background-size: cover; 加上很小的像素图,放大后实现炫彩背景效果。

使用 js canvas 随机生成小的像素图,设置为背景图。来实现随机背景效果

js 生成随机炫彩背景

代码如下:

<!--参考资料:https://ghost.org/xxxx/-->
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="renderer" content="webkit">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>随机炫彩背景</title>
<style>
/* css style */
html, body{margin:0; padding:0; min-height:100%;}
body {
background-size: cover;
background-image:url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAcAAAADCAYAAABfwxXFAAAAYklEQVQIWwFXAKj/ARBhmP8R6wMAHhsgABLvBAByKg0AterTAP7W8wABGnGg/1InOABMECEAy4vRAEcMAADE98oA4PjqAAEgYIL/MDs3AEcGLADxieMAQhUWAO/xzwCh778ANjsgSPo2oIsAAAAASUVORK5CYII=");
}
</style>
</head>
<body>
<h1 style="text-align:center; color:#fff;">随机炫彩背景</h1>
<script> // 生产随机数
// rand(10); 10
// rand([10, 100]); 10 ~ 100
// rand([50]); 0 ~ 50;
// rand([10,20,30]); 10|20|30
function rand(arr)
{
if (typeof arr === 'number')
{
return arr;
} var v = 0;
if (arr.length == 1)
{
v = Math.round(Math.random() * arr[0]);
}
else if (arr.length == 2)
{
var a = arr[0];
var b = arr[1]; v = Math.round(a + Math.random() * (b - a));
}
else if (arr.length > 2)
{
v = arr[Math.round(Math.random() * (arr.length - 1))];
} return v;
} // h 色调 s 饱和度 l 亮度
function randColorHsl(h, s, l)
{
h = h||[0, 360];
s = s||50;
l = l||50; return "hsl(" + rand(h) + ", " + rand(s) + "%, " + rand(l) + "%)";
} function randColorRgb(r, g, b)
{
r = r||[0, 255];
g = g||[0, 255];
b = b||[0, 255];
return "rgb(" + rand(r) + ", " + rand(g) + ", " + rand(b) + ")";
} var canvas = document.createElement('canvas'); // 像素大小控制图形复杂度
canvas.width = 7;
canvas.height = 3; var ctx=canvas.getContext('2d'); function randBackground()
{
for (var x=0; x<canvas.width; x++)
{
for (var y=0; y<canvas.height; y++)
{
// 随机颜色
// ctx.fillStyle = randColorHsl();
// ctx.fillStyle = randColorRgb();
ctx.fillStyle = randColorHsl(250, 50, [50, 80]);
ctx.fillRect(x,y,x+1,y+1);
}
} // 设置背景图
document.body.style.backgroundImage = 'url("' + canvas.toDataURL() + '")';
} window.setInterval(randBackground, 3000); </script>
</body>