提高JS动画的性能

时间:2019-11-23 20:01:19

标签: javascript performance animation

我用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()

欢迎提出任何建议。

1 个答案:

答案 0 :(得分:2)

沉重的负担归因于requestAnimationFrame一遍又一遍。一种方法是限制动画的帧频。知道人眼至少需要24 fps才能获得流畅的图像,因此您可以选择介于24-60 fps之间的fps(受监视器刷新频率限制为60Hz,具体取决于配置,但这通常是默认设置)。

这是a guide如何控制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();

The the difference between 30 fps and 60 fps

另一种以更少的工作量实现相同效果的技术是使用CSS动画(水平),并将背景波预先绘制为图像。