canvas鼠标连点交互粒子效果

代码语言:html

所属分类:粒子

代码描述:canvas鼠标连点交互粒子效果

代码标签: 交互 粒子 效果

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

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">

<style>
canvas{
  display: fixed;
/*   border: 1px solid red; */
}

body{
  margin: 0;
}
</style>

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

<script>
// color palette used: https://lospec.com/palette-list/slso-clr17

// log to tell me that codepen has refreshed
console.log('refresh');

const cnvs = document.getElementById('canvas');
const ctx = cnvs.getContext('2d');


const global = {
  mouseX: -5000,
  mouseY: -5000,
  width: 0,
  height: 0,
  distanceToGlow: 75,
  glowSpeed: 0.01,
  minGlow: 0.4,
  maxOffset: 20,
  gravitateSpeed: 0.01,
  canvasObjects: [],
  defaultSpeed: 0.05,
  init() {
    ctx.canvas.width = window.innerWidth;
    ctx.canvas.height = window.innerHeight;
    global.width = window.innerWidth;
    global.height = window.innerHeight;
    global.canvasObjects = [];
    while (global.canvasObjects.length < 500) {
      global.canvasObjects.push(new obj());
    }

  } };


class obj {
  constructor() {
    this.x = Math.random() * canvas.width;
    this.y = Math.random() * canvas.height;
    this.dx = global.defaultSpeed;
    this.direction = Math.random() * 360 * Math.PI / 180;
    this.yOffset = 0;
    this.xOffset = 0;
    this.angleToMouse = 0,
    this.offsetPercent = 0,
    this.closeToMouse = false;
    this.size = 4;
    this.opacity = global.minGlow;
    this.offscreen = false;
  }
  float() {
    this.direction += Math.random() < 0.5 ? 0.01 : -0.01;
    let dx = Math.cos(this.direction);
    let dy = Math.sin(this.direction);

    this.x += dx;
    this.y += dy;
  }
  mouseCheck() {
    let distance = Math.hypot(this.x - global.mouseX, this.y - global.mouseY);
    this.closeToMouse = distance < global.distanceToGlow;
    if (this.closeToMouse && this.opacity < 1) this.opacity += global.glowSpeed;
    if (!this.closeToMouse && this.opacity > global.minGlow) this.opacity -= global.glowSpeed;
    //  this.angleToMouse = CalcAngle(this.x, this.y, global.mouseX, global.mouseY);
    this.angleToMouse = angle(this.x, this.y, global.mouseX, global.mouseY);

    if (this.closeToMouse && this.offsetPercent < 1) this.offsetPercent += global.gravitateSpeed;
    if (!this.closeToMouse && this.offsetPercent > 0) this.offsetPercent -= global.gravitateSpeed;

    if (this.offsetPercent > 1) this.offsetPercent = 1;
    if (this.offsetPercent <.........完整代码请登录后点击上方下载按钮下载查看

网友评论0