前端样式实践:鼠标驱动的爱心粒子效果

开篇

本文基于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() - 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值