使用canvas实现鼠标跟随惊人特效!
投稿于 被查看 39068 次 评论:270
使用canvas实现鼠标跟随惊人特效!
最近在咕泡学院的VIP学习中看到利用canvas实现各种效果,我也仿照做一个。由于学习了vue和es6我决定用vue和es6的新特性来实现。
接下来让我们一步一步来创建一个。
第一步,创建html加入canvas
<template> <div class="canvasDiv"> <canvas id="myCanvas">当前浏览器不支持canvas</canvas> </div> </template>
如果浏览器不支持,请切换到最新的浏览器。
第二步,在mounted中对canvas进行初始化
由于要先加载canvas才能进行初始化,所以要在mounted中初始化。否则会报错。
let myCanvasEle = document.getElementById("myCanvas"); this.ctx = myCanvasEle.getContext("2d"); myCanvasEle.width = this.canvasWidth; myCanvasEle.height = this.canvasHeight; myCanvasEle.style.background = "black";
第三步,定义ball.js类
/** * 小球类 */ class Ball { constructor(ctx, x, y, color) { this.ctx = ctx; this.x = x; this.y = y; this.color = color; this.r = 40; } /** * 绘制小球 */ draw() { this.ctx.save(); this.ctx.beginPath(); this.ctx.arc(this.x, this.y, this.r, 0, 2 * Math.PI); this.ctx.fillStyle = this.color; this.ctx.fill(); this.ctx.restore(); } } /** * 移动球类继承球 */ class MoveBall extends Ball { constructor(ctx, x, y, color) { super(ctx, x, y, color); this.dx = random(-5, 5); this.dy = random(-5, 5); this.dr = random(3, 5); } //改变小球的x,y,r使小球动起来 update() { this.x += this.dx; this.y += this.dy; this.r -= this.dr; if(this.r < 0) { this.r = 0; } } }//欢迎加入全栈开发交流群一起学习交流:864305860 /** * 根据start和end生成随机数 */ const random = (start, end) => Math.floor(Math.random() * (end - start) + start); export default { getBall(ctx, x, y, color) { let moveBall = new MoveBall(ctx, x, y, color); return moveBall; } }
在ball.js中定义了两个类,一个小球类,一个是移动的小球,其中移动的小球继承了小球,暴露出一个getBall方法。
第四步,在main中调用
//增加移动事件 myCanvasEle.addEventListener("mousemove", (e) => { this.ballArray.push(ball.getBall(this.ctx, e.offsetX, e.offsetY, this.colorArray[Math.floor(Math.random() * (this.colorArray.length))])); }); //定时器 setInterval(() => { this.clear(); this.draw(); }, 50); //清屏 clear() { this.ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight); } //欢迎加入全栈开发交流群一起学习交流:864305860 //绘制 draw() { for(let i = 0; i < this.ballArray.length; i++) { this.ballArray[i].draw(); this.ballArray[i].update(); } }
获取源码
本次给大家推荐一个免费的学习群,里面概括移动应用网站开发,css,html,webpack,vue node angular以及面试资源等。
对web开发技术感兴趣的同学,欢迎加入Q群:864305860,不管你是小白还是大牛我都欢迎,还有大牛整理的一套高效率学习路线和教程与您免费分享,同时每天更新视频资料。
最后,祝大家早日学有所成,拿到满意offer,快速升职加薪,走上人生巅峰。
用户评论