demo 1:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<canvas id="cvs"></canvas>
<script>
// 配置
const config = {
color: false, // 图案颜色, 如果为false则使用随机颜色
size: 0, // 图案大小, 如果为0则使用随机大小
o: 0.4, // 递减值,数值越大图案消失越快
orange: 30, // 图案分散程度
opacity: 0.9, // 图案透明度,取值 0-1之间,在颜色随机的情况下有效
}
const cvs = document.querySelector('#cvs')
const ctx = cvs.getContext('2d')
const width = cvs.width = document.documentElement.clientWidth
const height = cvs.height = document.documentElement.clientHeight
// 绘制五角星
function renderStar(ctx, x, y, size, color) {
let R = size
let r = size / 2.5
//设置是个顶点的坐标,根据顶点制定路径
ctx.beginPath()
for (var i = 0; i < 5; i++) {
ctx.lineTo(Math.cos((18 + i * 72) / 180 * Math.PI) * R + x,
-Math.sin((18 + i * 72) / 180 * Math.PI) * R + y);
ctx.lineTo(Math.cos((54 + i * 72) / 180 * Math.PI) * r + x,
-Math.sin((54 + i * 72) / 180 * Math.PI) * r + y);
}
ctx.closePath()
ctx.strokeStyle = color
ctx.stroke()
}
function random (orange, min = 0) {
return parseInt(Math.random() * orange) + min
}
let stars = []
window.onmousemove = e => {
if (e.clientX % 2 === 0) return null
stars.push({
color: config.color || `rgba(${random(200,150)}, ${random(250,100)}, ${random(200, 100)}, ${config.opacity})`,
x: e.clientX + random(config.orange),
y: e.clientY + random(config.orange),
size: config.size || random(20) + 5,
orange: config.orange,
})
}
function animate() {
ctx.clearRect(0,0, width, height)
for (let i = 0; i < stars.length; i++) {
let item = stars[i]
item.size -= config.o
if (item.size <= 0) {
stars.splice(i, 1)
i--
}
renderStar(ctx, item.x, item.y, item.size, item.color)
}
window.requestAnimationFrame(animate)
}
animate()
</script>
</body>
</html>