首页 > 解决方案 > 提高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()

欢迎任何建议。

标签: javascriptperformanceanimation

解决方案


沉重的负载是由于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();

30 fps 和 60 fps 的区别

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


推荐阅读