通常我们在访问一些网站的时候,进行鼠标滑动的时候,会出现非常绚丽的效果,下面我们就用ES6的方式,编写一个简单的鼠标滑动的效果;
<canvas id="canvas"></canvas>
上面的是这个demo的html的标签,创建了一个canvas标签,其他的处理我们会放在js中进行,我会把所有的js代码都放在下面,可以参照观看:
// 0.定义一个取两个数之间的额随机数的方法 let newMath = (x, y) => { let tmp = y -x; return Math.floor(Math.random()*tmp + x); } //1.生成一个随机的色值 let randomRgbColor = () => { //随机生成RGBA颜色 let r = Math.floor(Math.random() * 256); //随机生成256以内r值 let g = Math.floor(Math.random() * 256); //随机生成256以内g值 let b = Math.floor(Math.random() * 256); //随机生成256以内b值 return `rgba(${r},${g},${b},.5)`; //返回rgb(r,g,b,a)格式颜色 } // 2.获取当前的画布 const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); canvas.width = 1000; canvas.height = 600; canvas.style.backgroundColor = '#000'; // 3.创建小球的类 class Ball{ constructor(x, y, color) { this.x = x; this.y = y; this.color = color; this.r = 40; } render() { ctx.save(); ctx.beginPath(); ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2); ctx.fillStyle = this.color; ctx.fill(); ctx.restore(); } } //4. 绘制移动的小球 class MoveBall extends Ball{ constructor(x, y, color) { super(x, y, color);//继承父类Ball的方法 this.dX = newMath(-5, 5); this.dY = newMath(-5, 5); this.dR = newMath(1, 3); } update() { this.x += this.dX; this.y += this.dY; this.r -= this.dR; if(this.r < 0) { this.r = 0; } } } //5.储存变化的小球 let ballArr = []; //6.监听鼠标的移动 canvas.addEventListener('mousemove',function(e) { ballArr.push(new MoveBall(e.offsetX, e.offsetY, randomRgbColor())); }) //7. 开启定时器,并开始画图 setInterval(function() { ctx.clearRect(0, 0, canvas.width, canvas.height); for(let i = 0, l = ballArr.length; i < l; i++) { ballArr[i].render(); ballArr[i].update(); } },50)
通过上面的创建,我们就可以实现我们需要的效果,具体表现可自行尝试;