【问题标题】:Sine wave animation performance advice正弦波动画性能建议
【发布时间】:2020-04-01 09:28:28
【问题描述】:

我正在尝试使用 javascript 创建一个正弦波动画,并且在获得我想要的外观方面取得了一些成功,但由于生成的矢量数量,我似乎遇到了性能问题。

我目前正在使用 p5js 库。这是我到目前为止生成的示例,是否有任何选项可以优化它以提高性能,同时保持细节/平滑度?

        function setup () {
            let size = min(windowWidth, windowHeight) * 0.96;
            size = floor(size);
            createCanvas(windowWidth, windowHeight);
            noiseSeed(random(50));
            frameRate(25); 
            noFill();
        }

        function windowResized () {
            let size = min(windowWidth, windowHeight);
            size = floor(size);
            resizeCanvas(windowWidth, windowHeight);
            noiseSeed(random(50));
            frameRate(25); 
            draw();
        }

        function draw () {
            clear();
            beginShape();


            const _o = millis() * 0.0005;
            const amount = 20;
            const ampl = ( 630 / ( windowHeight ) * 100 ) + 120;

            for(var k=0;k<amount;k++) {

                beginShape();

                const offset = (1 - k / amount) * 3;
                const detail = 10;

                for(var i=0;i<(width+detail);i+=detail) {

                    let y = height * 0.5;
                    y += Math.sin(i * 0.01 - _o + ( k / 50 ) + offset) * ampl;
                    y += Math.sin(i * 0.005 - _o + 5 + offset + noise(  50  ) ) * ampl;
                    console.log(i,y);
                    vertex(i, y);

                }
                stroke(255, 255, 255, (k/(amount - 1) * 100));
                frameRate(25); 
                endShape();
            }
        }

Codepen 示例: https://codepen.io/craiell/pen/zYGbLKm

我目前正在使用 P5js 库,但如果有其他库/方法,我愿意接受替代方案。任何指针将不胜感激。

【问题讨论】:

  • 这似乎是你可以让它运行的性能。 begin/endShape 功能非常耗费资源,当您只画线时,也许 line() 会是一个更好的选择?您必须保留以前的坐标。我喜欢这种效果。

标签: javascript animation trigonometry p5.js


【解决方案1】:

从嵌套循环中删除 console.log 行。这使得我的笔记本电脑上的动画流畅,即使我将帧速率提高到 60。

我对 P5js 不熟悉,但对frameRate() 的额外调用似乎是不必要的。

【讨论】:

    【解决方案2】:

    我脑海中的一些想法:

    1. for() 循环阻塞了胎面,使用foreach()map() 重写代码以优化流程

    2. 查看requestAnimationFrame()

    3. 浮点运算成本很高。看看是否可以生成可重用矢量坐标的缓存

    【讨论】:

    • 谢谢,我试试看。
    • p5 默认使用 requestAnimationFrame。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-29
    • 1970-01-01
    • 2022-09-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多