第一步,创建html加入canvas
[AppleScript]
纯文本查看
复制代码
1 2 3 4 5 | <template><div class="canvasDiv"><canvas id="myCanvas">当前浏览器不支持canvas</canvas></div></template> |
如果浏览器不支持,请切换到最新的浏览器。
第二步,在mounted中对canvas进行初始化
由于要先加载canvas才能进行初始化,所以要在mounted中初始化。否则会报错。
由于要先加载canvas才能进行初始化,所以要在mounted中初始化。否则会报错。
[AppleScript]
纯文本查看
复制代码
1 2 3 4 5 | let myCanvasEle = document.getElementById("myCanvas");this.ctx = myCanvasEle.getContext("2d");myCanvasEle.width = this.canvasWidth;myCanvasEle.height = this.canvasHeight;myCanvasEle.style.background = "black"; |
第三步,定义ball.js类
[AppleScript]
纯文本查看
复制代码
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | /*** 小球类*/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;}}}/*** 根据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中调用
第四步,在main中调用
[AppleScript]
纯文本查看
复制代码
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | //增加移动事件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();}} |
更多技术资讯可关注:gzitcast