// index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
body {
margin: 0;
color: #fff;
font-size: 24px;
background: #000;
}
body::before {
content: '';
position: absolute;
width: 100%;
height:100%;
left:0;
top: 0;
--start-density: 0.8;
--start-opacity: 1;
background-image: paint(skyDemo);
animation: shine 1s linear alternate infinite;
}
@keyframes shine {
from {
opacity: 1;
}
to {
opacity: 0.3;
}
}
</style>
</head>
<body>
<script>
if (!CSS in window || !CSS.paintWorklet) {
document.write('不支持 Houdini');
} else {
CSS.paintWorklet.addModule('sky.js')
}
</script>
</body>
</html>
// sky.js
class Sky {
constructor () {
this.starts = [];
}
static get inputProperties () {
return ['--start-density', '--start-opacity']
}
paint (ctx, paintSize, properties) {
let xMax = paintSize.width;
let yMax = paintSize.height;
ctx.fillRect(0, 0, xMax, yMax);
let starDensity = properties.get('--start-density').toString() || 1;
// 修正星星的密度
starDensity > 1 && (starDensity = 1);
// 设置数量
let allStarts = Math.round((xMax + yMax) * starDensity);
for (let i = 0; i < allStarts; i++) {
let x = Math.floor(Math.random() * xMax + 1);
let y = Math.floor(Math.random() * yMax + 1);
let size = Math.floor(Math.random() * 2 + 1);
// 设置透明度
const opacityOne = Math.floor(Math.random() * 9 + 1);
const opacityTwo = Math.floor(Math.random() * 9 + 1);
const hue = Math.floor(Math.random() * 360 + 1)
const opacity = +('.' + (opacityOne + opacityTwo)) * starDensity;
ctx.fillStyle = `hsla(${hue}, 30%, 50%, ${opacity})`;
ctx.fillRect(x, y, size, size);
}
}
}
registerPaint('skyDemo', Sky);
网友评论