人生处处是舞台,人需要聚光灯,代码也需要聚光灯,这里就分享一个如何做聚光灯的效果,欢迎大家将代码拿去尝试;
1、效果展示
2、代码分享
<!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>
</head>
<style></style>
<body>
<h1>hello world</h1>
</body>
<script>
document.querySelector('style').append(`canvas {
position: fixed;
left:0;
top: 0;
z-index: 9999;
pointer-events: none;
}`)
document.body.appendChild(document.createElement('canvas'))
const cvs = document.querySelector('canvas')
const ctx = cvs.getContext('2d')
cvs.width = document.documentElement.clientWidth
cvs.height = document.documentElement.clientHeight
const p = {
x: 0,
y: 0,
r: 50
}
document.onmousemove = e => {
p.x = e.clientX
p.y = e.clientY
render()
}
const render = () => {
ctx.beginPath()
ctx.clearRect(0, 0, cvs.width, cvs.height)
var radial = ctx.createRadialGradient(p.x, p.y, p.r, p.x, p.y, p.r * 3);
radial.addColorStop(0, 'rgba(255, 255, 255, 0)');
radial.addColorStop(1, 'rgba(0, 0, 0, 0.5)');
ctx.fillStyle = radial;
ctx.fillRect(0, 0, cvs.width, cvs.height);
}
render()
window.onresize = () => {
cvs.width = document.documentElement.clientWidth
cvs.height = document.documentElement.clientHeight
render()
}
</script>
</html>