如何获得此画布动画脚本在Firefox中工作?

时间:2018-10-13 21:34:59

标签: javascript firefox html5-canvas

我写了这个画布动画脚本,希望能在我的投资组合网站上使用它,但是在Firefox中它基本上是不起作用的,我不确定为什么。该脚本在画布上绘制缓慢旋转的星星,如果按住鼠标按钮,它们将旋转得更快,从而创建轨迹。它在chrome浏览器中很棒,但是在Firefox中却非常慢且不稳定。

let canvas = document.querySelector('canvas');
let c = canvas.getContext('2d');

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

let mouse = {
  x: window.innerWidth / 2,
  y: window.innerHeight / 2
}

let stars = [];
const starCount = 800;

class Star {
  constructor(x, y, radius, color){
    this.x = x;
    this.y = y;
    this.radius = radius;
    this.color = color;

    this.draw = () => {
      c.save(); 
      c.beginPath(); 
      c.arc(this.x, this.y, this.radius, 0, Math.PI * 2); 
      c.fillStyle = this.color;
      c.shadowColor = this.color;
      c.shadowBlur = 15;
      c.fill(); 
      c.closePath(); 
      c.restore(); 
    };

    this.update = () => {
      this.draw();
    };
  }
}

let colors = [
  "#A751CC",
  "#DE9AF9",
  "#F9E0F9",
  "#B5ECFB",
  "#5F86F7"
];


(initializeStars = () =>{
  for(let i = 0; i < starCount; i++){
    let randomColorIndex = Math.floor(Math.random() * 5);
    let randomRadius = Math.random() * 2;
    let x = (Math.random() * (canvas.width + 400)) - (canvas.width + 400) / 2; 
    let y = (Math.random() * (canvas.width + 400)) - (canvas.width + 400) / 2;
    stars.push(new Star(x, y, randomRadius, colors[randomColorIndex]));
  }
})();

let opacity = 1;
let speed = 0.0005;
let time = 0;

let spinSpeed = desiredSpeed => {
  speed += (desiredSpeed - speed) * 0.01;
  time += speed;
  return time;
}

let starOpacity = (desiredOpacity, ease) => {
  opacity += (desiredOpacity - opacity) * ease;
  return c.fillStyle = `rgba(18, 18, 18, ${opacity})`;
}

let animate = () => {
  window.requestAnimationFrame(animate);
  c.save();

  if(mouseDown){
    starOpacity(0.01, 0.03);
    spinSpeed(0.012);
  }else{
    starOpacity(1, 0.01);
    spinSpeed(0.001);
  }

  c.fillRect(0,0, canvas.width, canvas.height);
  c.translate(canvas.width / 2, canvas.height / 2);
  c.rotate(time);

  for(let i = 0; i < stars.length; i++){
    stars[i].update();
  }

  c.restore();

}


window.addEventListener('mousemove', e => {
  mouse.x = e.clientX - canvas.width / 2;
  mouse.y = e.clientY - canvas.height / 2;
});


window.addEventListener('resize', () => {
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;

  stars = [];
  initializeStars();
});


let mouseDown = false;

window.addEventListener("mousedown", () =>{
  mouseDown = true;
});

window.addEventListener("mouseup", () => {
  mouseDown = false;
});

animate();

这是Code Pen上的演示的link;任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:1)

  1. 您可以使用rect而不是arc来绘制星星:

    c.rect(this.x,this.y,2 * this.radius,2 * this.radius);

  2. 消除模糊这是非常昂贵的:

    // c.shadowBlur = 15;

您可以使用径向渐变,从中间的不透明代替他的透明。