开篇
本文基于canvas和vue3实现了一个动态粒子爱心特效。
效果展示
视频演示
爱心粒子
截图
本文目标
- 使用 HTML5 Canvas 和 JavaScript 创建一个动态粒子系统。
- 实现粒子在鼠标位置周围形成一个爱心形状。
- 通过交互(鼠标移动)控制爱心形状的变化。
具体实现
<template>
<div class="quantum-container">
<!-- 量子云效果的画布 -->
<canvas ref="canvas" class="quantum-canvas"></canvas>
</div>
</template>
<script setup>
import {
ref, onMounted, onUnmounted } from "vue";
const canvas = ref(null);
let ctx = null;
let width = 0;
let height = 0;
let particles = [];
let mouseX = null;
let mouseY = null;
let animationFrame = null;
// 粒子类 - 用于创建和管理单个粒子的行为
class Particle {
constructor() {
this.reset(true);
}
// 重置粒子属性
// @param isInit - 是否是初始化状态
reset(isInit = false) {
if (isInit) {
// 初始化时随机分布在画布上
this.x = Math.random() * width;
this.y = Math.random() * height;
// 设置初始速度向量
this.vx = (Math.random() - 0.5) * 4;
this.vy = (Math.random() - 0.5) * 4;
} else {
// 非初始化时从画布边缘重生
const side = Math.floor(Math.random() * 4);
switch (side) {
case 0: // 从上方进入
this.x = Math.random() * width;
this.y = -10;
break;
case 1: // 从右方进入
this.x = width + 10;
this.y = Math.random() * height;
break;
case 2: // 从下方进入
this.x = Math.random() * width;
this.y = height + 10;
break;
case 3: // 从左方进入
this.x = -10;
this.y = Math.random() * height;
break;
}
// 设置重生后的初始速度
this.vx = (Math.random() -