canvas实现可配置参数的线条粒子动画效果代码

代码语言:html

所属分类:粒子

代码描述:canvas实现可配置参数的线条粒子动画效果代码

代码标签: canvas 配置 参数 线条 粒子 动画

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

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

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

  
  
<style>
body {
  background: #111;
  overflow: hidden;
  height: 100vh;
  width: 100vw;
  margin: 0;
}

canvas {
  position: absolute;
  width: 100vw;
  height: 100vh;
}
</style>


  
</head>

<body translate="no">
  <canvas id="canvas"></canvas>

      <script  type="module">
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

const defaultConfig = {
  count: 500,
  distance: 12,
  size: 2,
  speed: 0.5 };


const config = structuredClone(defaultConfig);

let centerX = 0,
centerY = 0,
points = [];

const init = () => {
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;
  centerX = canvas.width / 2;
  centerY = canvas.height / 2;
  points = Array.from({ length: config.count }).map(() => ({
    x: centerX,
    y: centerY,
    hue: Math.random() * 360,
    speed: Math.random() * 0.5 + config.speed,
    alpha: Math.random() * 0.5 + 0.5 }));

  ctx.fillStyle = "rgba(0, 0, 0, 1)";
  ctx.fillRect(0, 0, canvas.width, canvas.height);
};

init();

window.addEventListener("resize", init);

const randomStep = () => (Math.random() - 0.5) * config.distance * 2;

const draw = () => {
  ctx.fillStyle = "rgba(17, 17, 17, 0.1)";
  ctx.fillRect(0, 0, canvas.width, canvas.height);

  points.forEach(point => {
    const { x, y } = point;

    point.x += randomStep() * point.speed;
    point.y += randomStep() * point.speed;

    ctx.beginPath();
    ctx.moveTo(x, y);
    ctx.lineTo(point.x, point.y);
    ctx.strokeStyle = `hsla(${point.hue}, 72%, 60%, ${point.alpha})`;
    ctx.lineWidth = config.size;
    ctx.stroke();

    point.hue = (point.hue + 0.3) % 360;

    const dx = point.x - centerX;
    const dy = point.y - centerY;
    const distan.........完整代码请登录后点击上方下载按钮下载查看

网友评论0