返回
用 ES6 的 class 类继承实现炫彩小球效果
前端
2024-01-06 22:38:57
## 利用 ES6 的 class 类继承实现绚丽小球效果
在这个数字时代,人们对视觉效果的要求越来越高,而动画效果无疑是吸引眼球的利器之一。在网页设计中,动画效果可以用来增强用户体验,提高网站的整体视觉效果。
今天,我们将利用 ES6 的 class 类继承来实现一种绚丽的小球效果。当鼠标在 Canvas 画布上移动时,鼠标所在的位置会生成随机颜色的小球,并且这些小球会随着时间而运动和变化。这种效果非常适合用在游戏、互动网站或其他需要视觉效果的地方。
### 准备工作
在开始之前,我们需要准备以下工具:
* 文本编辑器
* 浏览器
* JavaScript 运行环境(如 Node.js)
### 创建画布
首先,我们需要创建一个 Canvas 画布。Canvas 是 HTML5 中用于创建图形和动画的元素。我们可以使用以下代码来创建一个 Canvas 画布:
```html
<canvas id="canvas" width="500" height="500"></canvas>
这段代码将在 HTML 文档中创建一个具有 500 像素宽和 500 像素高的 Canvas 画布。
获取画布上下文
接下来,我们需要获取 Canvas 画布的上下文。上下文是用于在 Canvas 画布上绘制图形和动画的对象。我们可以使用以下代码来获取 Canvas 画布的上下文:
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
定义小球类
现在,我们需要定义一个名为 Ball
的类来表示小球。这个类将包含小球的位置、颜色和半径等属性,以及用于绘制小球的方法。
class Ball {
constructor(x, y, radius, color) {
this.x = x;
this.y = y;
this.radius = radius;
this.color = color;
this.vx = Math.random() * 10 - 5; // 初始速度
this.vy = Math.random() * 10 - 5;
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, 2 * Math.PI);
ctx.fillStyle = this.color;
ctx.fill();
}
update() {
this.x += this.vx;
this.y += this.vy;
// 边界检测
if (this.x + this.radius > canvas.width || this.x - this.radius < 0) {
this.vx = -this.vx;
}
if (this.y + this.radius > canvas.height || this.y - this.radius < 0) {
this.vy = -this.vy;
}
}
}
创建小球实例
接下来,我们需要创建小球实例。我们可以使用以下代码来创建 10 个随机颜色的小球:
const balls = [];
for (let i = 0; i < 10; i++) {
const x = Math.random() * canvas.width;
const y = Math.random() * canvas.height;
const radius = Math.random() * 10 + 5;
const color = `rgb(${Math.random() * 255}, ${Math.random() * 255}, ${Math.random() * 255})`;
const ball = new Ball(x, y, radius, color);
balls.push(ball);
}
绘制小球
现在,我们需要绘制小球。我们可以使用以下代码来绘制小球:
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (let i = 0; i < balls.length; i++) {
balls[i].draw();
}
requestAnimationFrame(draw);
}
draw();
更新小球
最后,我们需要更新小球的位置。我们可以使用以下代码来更新小球的位置:
function update() {
for (let i = 0; i < balls.length; i++) {
balls[i].update();
}
requestAnimationFrame(update);
}
update();
完整代码
以下