当前位置:主页 > JavsScript库 > 动画 >

JavaScript和 Canvas的交互式星座效果
栏目分类:动画   发布日期:2021-09-07   浏览次数:

一种交互式星座效果,可在鼠标移动时自动生成连接的粒子。

使用:

1. 创建一个在其上呈现星座效果的 HTML5 画布元素。

<canvas id="mycanvas"></canvas>

2. 将您自己的样式应用到画布上。

#mycanvas {
  position: absolute;
  background-color: black;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
}

3.创建星座效果的主要脚本。

const canvas = document.getElementById('mycanvas');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
let particles = [];
window.addEventListener('resize', function (e) {
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;
});
let hueCol = 0;
const mouse = {
  x: undefined,
  y: undefined,
}
canvas.addEventListener('click', function (e) {
  mouse.x = e.x;
  mouse.y = e.y;
  for (let i = 0; i < 5; i++) {
    particles.push(new Particle);
  }
})
canvas.addEventListener('mousemove', function (e) {
  mouse.x = e.x;
  mouse.y = e.y;
  for (let i = 0; i < 5; i++) {
    particles.push(new Particle);
  }
})
class Particle {
  constructor() {
    this.x = mouse.x;
    this.y = mouse.y;
    this.speedX = Math.random() * 3 - 1.5;
    this.speedY = Math.random() * 3 - 1.5;
    this.color = 'hsl(' + hueCol + ', 100%, 50%)';
    this.size = Math.random() * 5 + 1;
  }
  update() {
    this.x += this.speedX;
    this.y += this.speedY;
    this.size -= 0.1;
  }
  draw() {
    ctx.fillStyle = this.color;
    ctx.beginPath();
    ctx.arc(this.x, this.y, 5, 0, Math.PI * 2);
    ctx.fill();
  }
}
function handleParticles() {
  for (var i = 0; i < particles.length; i++) {
    particles[i].update();
    particles[i].draw();
    for (var j = i + 1; j < particles.length; j++) {
      const dx = particles[j].x - particles[i].x;
      const dy = particles[j].y - particles[i].y;
      const distance = dx * dx + dy * dy;
      if (distance < 10000) {
        ctx.beginPath();
        ctx.strokeStyle = particles[i].color;
        ctx.lineWidth = 0.3;
        ctx.moveTo(particles[i].x, particles[i].y);
        ctx.lineTo(particles[j].x, particles[j].y);
        ctx.stroke();
      }
    }
    if (particles.size < 0.3) {
      particles.splice(i, 1);
      i--;
    }
  }
}
function animate() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  // ctx.fillStyle = 'rgba(0, 0, 0, 0.1)';
  // ctx.fillRect(0, 0, canvas.width, canvas.height);
  handleParticles();
  hueCol += 2;
  requestAnimationFrame(animate);
}
animate();

官方网站:https://github.com/krithikagoyal/Constellation-effect

声源:本站内容均来自互联网,仅供交流学习之用,请勿作商业用途,所有资源版权归原作者所有。如果有侵犯到您的权益,请联系本站删除,谢谢合作!
jQuery库 JavsScript库 Html5库 CSS3库