canvas文字粒子交互动画显示效果代码

代码语言:html

所属分类:粒子

代码描述:canvas文字粒子交互动画显示效果代码

代码标签: canvas 文字 粒子 交互 动画 显示

下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开

<!DOCTYPE html>
<html lang="en" >

<head>
  <meta charset="UTF-8">
  

  
  
<style>
body {
  display: grid;
  place-items: center;
  height: 100dvh;
  background: #222;
}

canvas {
  position: fixed;
  inset: 0;
  width: 100%;
  height: 100%;
}
</style>


  
  
</head>

<body translate="no">
  <div>
	<canvas></canvas>
</div>
  
      <script >
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

const particles = [];
const particleCount = 1200;
const textArray = ["Design.", "Code.", "Coffee."];
let currentTextIndex = 0;
let nextTextTimeout;
let textCoordinates = [];

const mouse = {
  x: -500,
  y: -500,
  radius: 50 };


class Particle {
  constructor(x, y) {
    this.x = x;
    this.y = y;
    this.size = 1;
    this.baseX = x;
    this.baseY = y;
    this.density = Math.random() * 30 + 1;
    this.color = "white";
    this.history = [];
  }

  update() {
    let dx = mouse.x - this.x;
    let dy = mouse.y - this.y;
    let distance = Math.sqrt(dx * dx + dy * dy);

    if (distance < mouse.radius) {
      let forceDirectionX = dx / distance;
      let forceDirectionY = dy / distance;
      let maxDistance = mouse.radius;
      let force = (maxDistance - distance) / maxDistance;
      let directionX = forceDirectionX * force * this.density;
      let directionY = forceDirectionY * force * this.density;

      this.x -= directionX;
      this.y -= directionY;
    } else {
      this.x += (this.baseX - this.x) * 0.05;
      this.y += (this.baseY - this.y) * 0.05;
    }

    this.history.push({ x: this.x, y: this.y });
    if (this.history.length > 10) {
      this.history.shift();
    }

    const speed = Math.sqrt(
    (this.baseX - this.x) ** 2 + (this.baseY - this.y) ** 2);

    const hue = speed / 100 * 360;

    this.color = `hsl(${hue}, 100%, ${100 - speed / 5}%)`;

    if (this.history.length > 10) {
      this.history.shift();
    }
  }

  draw() {
    ctx.beginPath();
    ctx.moveTo(this.history[0].x, this.history[0].y);
    for (let i = 1; i < this.history.length; i++) {
      ctx.lineTo(this.history[i].x, this.history[i].y);
    }
    ctx.strokeStyle = this.color;
    ctx.stroke();

    ctx.fillStyle = this.color;
    ctx.beginPath();
    ctx.arc(this.x, this.y, this.size, 0,.........完整代码请登录后点击上方下载按钮下载查看

网友评论0