最近在咕泡学院的 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();
- }
- }
获取源码
来源: http://www.qdfuns.com/article/51117/67e7142c2ffca09ff1ab55a104d2eb7c.html