首页 > 解决方案 > 如何使用 javascript 优化粒子

问题描述

我第一次使用 javascript 创建粒子,我不确定下面的代码是否经过优化。

当我在屏幕上创建 100 个粒子时,我没有注意到 fps 下降太多。

当连续发生多次点击时,fps 会大幅下降。

这是可以理解的,但是有没有办法进一步优化这段代码,以便多次点击可以保持更高的帧速率?

var fps = document.getElementById("fps");
var startTime = Date.now();
var frame = 0;

function tick() {
  var time = Date.now();
  frame++;
  if (time - startTime > 1000) {
      fps.innerHTML = (frame / ((time - startTime) / 1000)).toFixed(1);
      startTime = time;
      frame = 0;
    }
  window.requestAnimationFrame(tick);
}
tick();

function pop (target) {
  let amount = 100;
  // Quick check if user clicked the button using a keyboard
    const bbox = target.getBoundingClientRect();
    const x = bbox.left + bbox.width / 2;
    const y = bbox.top + bbox.height / 2;
    for (let i = 0; i < 100; i++) {

      createParticle(x, y);
    }
  
  
}
function createParticle (x, y) {
  const particle = document.createElement('particle');
  document.body.appendChild(particle);
  let width = Math.floor(Math.random() * 30 + 8);
  let height = width;
  let destinationX = (Math.random() - 0.5) * 1000;
  let destinationY = (Math.random() - 0.5) * 1000;
  let rotation = Math.random() * 2000;
  let delay = Math.random() * 200;

      particle.style.background = `hsl(${Math.random() * 90 + 270}, 70%, 60%)`;
      particle.style.border = '1px solid white';
  
  particle.style.width = `${width}px`;
  particle.style.height = `${height}px`;
  const animation = particle.animate([
    {
      transform: `translate(-50%, -50%) translate(${x}px, ${y}px) rotate(0deg)`,
      opacity: 1
    },
    {
      transform: `translate(-50%, -50%) translate(${x + destinationX}px, ${y + destinationY}px) rotate(${rotation}deg)`,
      opacity: 0
    }
  ], {
    duration: Math.random() * 1000 + 5000,
    easing: 'cubic-bezier(0, .9, .57, 1)',
    delay: delay
  });
  animation.onfinish = removeParticle;
}
function removeParticle (e) {
  e.srcElement.effect.target.remove();
}
document.querySelector(".confetti").addEventListener("click",()=>{pop(document.querySelector(".confetti"));}
);
particle {
  position: fixed;
  top: 0;
  left: 0;
  opacity: 0;
  pointer-events: none;
  background-repeat: no-repeat;
  background-size: contain;
}
<div class="wrapper">
  <span id="fps">--</span> FPS</div>
  <div class="confetti">Square particles</div>

</div>

标签: javascripthtml

解决方案


如果你可以添加一个画布,而不是添加元素和样式,你可以在画布上绘制东西会更快。然后,它可以更快。如果你不知道如何在 JavaScript 中使用画布,你可能想在 W3Schools 之类的东西上搜索它,因为他们有很多东西可以向他们学习。

我希望这有帮助。如果您有任何反馈,请给我任何反馈。我是 Stack Overflow 的新手,所以我想知道如何改进。感谢和快乐的编码!


推荐阅读