正弦波动画性能建议

问题描述 投票:0回答:1

我正在尝试使用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库,但是如果还有其他库/方法,我也可以选择。任何指针将不胜感激。

javascript animation trigonometry p5.js
1个回答
0
投票

一些想法浮出水面:

  1. [for()循环正在阻塞,请使用foreach()map()重写代码以优化流程

  2. 签出requestAnimationFrame()

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

0
投票

从嵌套循环中删除requestAnimationFrame()行。这样可使动画在笔记本电脑上流畅播放。

我不熟悉P5js,但是似乎没有必要额外调用console.log

© www.soinside.com 2019 - 2024. All rights reserved.