gpt4 book ai didi

javascript - 如何让这个 Canvas 动画脚本在 Firefox 中运行?

转载 作者:行者123 更新时间:2023-12-03 00:56:41 25 4
gpt4 key购买 nike

我编写了这个 Canvas 动画脚本,希望在我的作品集网站上使用它,但它在 Firefox 中基本上不起作用,我不知道为什么。该脚本在 Canvas 上绘制缓慢旋转的星星,如果按住鼠标按钮,它们会旋转得更快,从而创建轨迹。它在 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();

这是link Code Pen 上的演示;如有任何帮助,我们将不胜感激。

最佳答案

  1. 您可以使用矩形而不是圆弧来绘制星星:

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

  2. 去除模糊非常昂贵:

    //c.shadowBlur = 15;

您可以使用从中心不透明到透明的径向渐变来代替它。

关于javascript - 如何让这个 Canvas 动画脚本在 Firefox 中运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52797542/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com