javascript - 提高js动画的性能
问题描述
我用 javascript 制作了一个正弦波动画,其中正弦波下方的区域填充了浅蓝色。但是当我运行代码时,我的计算机开始发热并出现延迟。这也可能是因为我的电脑现在已经很破旧了,但我真的很想知道如何优化这段代码,或者如果可能的话,用其他不那么性能密集的东西重新创建效果。
正弦波动画: https ://jsfiddle.net/x2audoqk/13/
编码:
const canvas = document.querySelector("canvas")
const c = canvas.getContext("2d")
canvas.width = innerWidth
canvas.height = innerHeight
window.addEventListener("resize", function () {
canvas.width = innerWidth
canvas.height = innerHeight
wave.y = canvas.height / 1.5
wave.length = -4.5 / canvas.width
amplitude = canvas.width / 35
})
const wave = {
y: canvas.height / 1.5,
length: -4.5 / canvas.width,
amplitude: canvas.width / 25,
frequency: 0.0045
}
let increment = wave.frequency
function animate() {
requestAnimationFrame(animate)
// Deletes previous waves
c.clearRect(0, 0, canvas.width, canvas.height)
c.beginPath()
// Get all the points on the line so you can modify it with Sin
for (let i = 0; i <= canvas.width; i++) {
c.moveTo(i, wave.y + Math.sin(i * wave.length + increment) * wave.amplitude * Math.sin(increment))
c.lineTo(i, canvas.height)
}
// Fill the path
c.strokeStyle = 'rgba(1, 88, 206, .25)'
c.stroke()
increment += wave.frequency
c.closePath()
}
animate()
欢迎任何建议。
解决方案
沉重的负载是由于requestAnimationFrame
它一遍又一遍地运行。一种方法是限制动画的帧速率。知道人眼至少需要 24 fps 才能获得流畅的图像,您可以选择 24-60 fps 之间的 fps(受限于高达 60Hz 的显示器刷新率,具体取决于配置,但这主要是默认设置)。
这是如何控制fps的指南
var fps = 30;
var now;
var then = Date.now();
var interval = 1000/fps;
var delta;
function animate() {
requestAnimationFrame(animate);
now = Date.now();
delta = now - then;
if (delta > interval) {
then = now - (delta % interval);
//your code drawing here
}
}
animate();
另一种以较少工作量实现相同效果的技术是使用 CSS 动画(水平),将背景波预绘制为图像。
推荐阅读
- sql - SQL Developer doesn't recognize right outer join ORA-00905: missing keyword
- python - 有没有办法在 python 的单行中使用 for 打印范围
- php - How to increment php array?
- php - How to add two images per slide from mysql (PHP Presentation)?
- operating-system - How drivers work out of the box in x86 and not in embedded computers like Android phone
- homebrew - brew extract --version=9.25 ghostscript [tap]什么是tap?
- minizinc - Minizinc constraint against recursive function
- unity3d - 使用引用的纹理从搅拌机将 .dae 导入 Unity
- python - Why is pywin32 service not stopping correctly?
- java - Variable 'Button' never assigned (Java using android studio)