100行代码整一个鼠标电火花特效
分类: Java 标签:
2020-11-02 20:01:21 1570浏览
以下上代码,关键地方都注释了
<!DOCTYPE html>
<html>
<head>
<style>
*{
margin: 0;
padding: 0;
overflow: hidden;
}
</style>
</head>
<body>
<canvas id="c"></canvas>
</body>
<script>
// 定义一个 光效类
class Light{
constructor() {
const $ = s => document.querySelector(s);
// 获取cacnvas 元素 并设置宽高
this.c = $('#c');
this.ctx = c.getContext('2d');
this.c.width = window.innerWidth;
this.c.height = window.innerHeight;
this.pointers = [{ x: this.cx , y: this.cy } ];
this.event();
this.render();
// 利用浏览器api来循环渲染动画
window.requestAnimationFrame( this.render.bind(this));
}
event(){
// 把鼠标位置添加进路劲里
window.addEventListener('mousemove', e=>{
let o = this.pointers.length > 36 ? this.pointers.shift() : {}
o.x = e.clientX;
o.y = e.clientY;
this.pointers.push(o)
})
}
render(){
const {ctx} = this;
ctx.lineWidth = 1;
ctx.fillStyle = '#000';
ctx.fillRect( 0 , 0, this.c.width,this.c.height)
//添加一次当前路劲
let o = this.pointers.length > 36 ? this.pointers.shift() : {}
o.x = this.pointers[this.pointers.length - 1].x;
o.y = this.pointers[this.pointers.length - 1].y;
this.pointers.push(o)
let cx,cy;
ctx.beginPath();
// 设置光晕
ctx.shadowBlur = 3;
ctx.shadowColor = '#fcc';
// 渲染路劲
this.pointers.forEach( ({x,y},idx)=>{
cx = x;
cy = y;
// 画路劲点上的电光
ctx.moveTo(cx ,cy);
const r = (this.pointers.length - idx) / 2;
ctx.lineTo( cx + Math.random() * r - r /2 , cy + Math.random() * r - r /2);
ctx.lineTo( cx + Math.random() * r - r /2 , cy + Math.random() * r - r /2);
ctx.lineTo( cx + Math.random() * r - r /2 , cy + Math.random() * r - r /2);
ctx.strokeStyle = `rgba(255,255,255,${Math.random() * 0.6 })`
ctx.stroke();
})
// 这里渲染一些小光点
for(let i = 0; i< ~~( Math.random() * 7); i++){
ctx.beginPath();
ctx.fillStyle = `rgba(255,255,255,${Math.random() })`
ctx.arc( cx + Math.random() * 150 - 150 /2 , cy + Math.random() * 150 - 150 /2 , Math.random() + 1, 0,2*Math.PI)
ctx.fill();
}
window.requestAnimationFrame( this.render.bind(this));
}
}
new Light();
</script>
</html>
好博客就要一起分享哦!分享海报