javascript 画布粒子、碰撞和性能

rsl1atfo  于 2023-01-24  发布在  Java
关注(0)|答案(4)|浏览(109)

我正在创建一个Web应用程序,它有一个交互式的背景,粒子四处弹跳。在任何时候,屏幕上都有大约200个圆形粒子,最多大约800个粒子。为粒子运行的一些碰撞和效果是下面的原型。我想知道我是否可以通过使用Web工作者来做这些计算来提高性能?

/**
*   Particles
*/

Jarvis.prototype.genForegroundParticles = function(options, count){

    count = count || this.logoParticlesNum;

    for (var i = 0; i < count; i++) {
        this.logoParticles.push(new Particle());
    }

}

Jarvis.prototype.genBackgroundParticles = function(options, count){

    count = count || this.backgroundParticlesNum;

    for (var i = 0; i < count; i++) {
        this.backgroundParticles.push(new Particle(options));
    }

}

Jarvis.prototype.motion = {
    linear : function(particle, pIndex, particles){
        particle.x += particle.vx
        particle.y += particle.vy
    },
    normalizeVelocity : function(particle, pIndex, particles){

        if (particle.vx - particle.vxInitial > 1) {
            particle.vx -= 0.05;
        } else if (particle.vx - particle.vxInitial < -1) {
            particle.vx += 0.05;
        }

        if (particle.vy - particle.vyInitial > 1) {
            particle.vy -= 0.05;
        } else if (particle.vx - particle.vxInitial < -1) {
            particle.vy += 0.05;
        }

    },
    explode : function(particle, pIndex, particles) {

        if (particle.isBottomOut()) {
            particles.splice(pIndex, 1);
        } else {
            particle.x += particle.vx;
            particle.y += particle.vy;
            particle.vy += 0.1;
        }

        if (particles.length === 0){
            particles.motion.removeMotion("explode");
            this.allowMenu = true;
        }       

    }
}

Jarvis.prototype.collision = {
    boundingBox: function(particle, pIndex, particles){

        if (particle.y > (this.HEIGHT - particle.radius) || particle.y < particle.radius) {
            particle.vy *= -1;
        }

        if(particle.x > (this.WIDTH - particle.radius) || particle.x < particle.radius) {
            particle.vx *= -1;
        }
    },
    boundingBoxGravity: function(particle, pIndex, particles){
        // TODO: FIX GRAVITY TO WORK PROPERLY IN COMBINATION WITH FX AND MOTION
        if (particle.y > (this.HEIGHT - particle.radius) || particle.y < particle.radius) {
            particle.vy *= -1;
            particle.vy += 5;
        } 

        if(particle.x > (this.WIDTH - particle.radius) || particle.x < particle.radius) {
            particle.vx *= -1;
            particle.vx += 5;
        }

    },
    infinity: function(particle, pIndex, particles){

        if (particle.x > this.WIDTH){
            particle.x = 0;
        }

        if (particle.x < 0){
            particle.x = this.WIDTH;
        }

        if (particle.y > this.HEIGHT){
            particle.y = 0;
        }       

        if (particle.y < 0) {
            particle.y = this.HEIGHT;
        }

    }
}

Jarvis.prototype.fx = {
    link : function(particle, pIndex, particles){

        for(var j = pIndex + 1; j < particles.length; j++) {

            var p1 = particle;
            var p2 = particles[j];
            var particleDistance = getDistance(p1, p2);

            if (particleDistance <= this.particleMinLinkDistance) {
                this.backgroundCtx.beginPath();
                this.backgroundCtx.strokeStyle = "rgba("+p1.red+", "+p1.green+", "+p1.blue+","+ (p1.opacity - particleDistance / this.particleMinLinkDistance) +")";
                this.backgroundCtx.moveTo(p1.x, p1.y);
                this.backgroundCtx.lineTo(p2.x, p2.y);
                this.backgroundCtx.stroke();
                this.backgroundCtx.closePath();
            }
        }
    },
    shake : function(particle, pIndex, particles){

        if (particle.xInitial - particle.x >= this.shakeAreaThreshold){
            particle.xOper = (randBtwn(this.shakeFactorMin, this.shakeFactorMax) * 2) % (this.WIDTH);
        } else if (particle.xInitial - particle.x <= -this.shakeAreaThreshold) {
            particle.xOper = (randBtwn(-this.shakeFactorMax, this.shakeFactorMin) * 2) % (this.WIDTH);
        }

        if (particle.yInitial - particle.y >= this.shakeAreaThreshold){
            particle.yOper = (randBtwn(this.shakeFactorMin, this.shakeFactorMax) * 2) % (this.HEIGHT);
        } else if (particle.yInitial - particle.y <= -this.shakeAreaThreshold) {
            particle.yOper = (randBtwn(-this.shakeFactorMax, this.shakeFactorMin) * 2) % (this.HEIGHT);
        }       

        particle.x += particle.xOper;
        particle.y += particle.yOper;

    },
    radialWave : function(particle, pIndex, particles){

        var distance = getDistance(particle, this.center);

        if (particle.radius >= (this.dim * 0.0085)) {
            particle.radiusOper = -0.02;
        } else if (particle.radius <= 1) {
            particle.radiusOper = 0.02;
        }

        particle.radius += particle.radiusOper * particle.radius;
    },
    responsive : function(particle, pIndex, particles){

        var newPosX = (this.logoParticles.logoOffsetX + this.logoParticles.particleRadius) + (this.logoParticles.particleDistance + this.logoParticles.particleRadius) * particle.arrPos.x;
        var newPosY = (this.logoParticles.logoOffsetY + this.logoParticles.particleRadius) + (this.logoParticles.particleDistance + this.logoParticles.particleRadius) * particle.arrPos.y;

        if (particle.xInitial !== newPosX || particle.yInitial !== newPosY){

            particle.xInitial = newPosX;
            particle.yInitial = newPosY;
            particle.x = particle.xInitial;
            particle.y = particle.yInitial;

        }

    },
    motionDetect : function(particle, pIndex, particles){

        var isClose = false;
        var distance = null;

        for (var i = 0; i < this.touches.length; i++) {

            var t = this.touches[i];

            var point = {
                x : t.clientX,
                y : t.clientY
            }

            var d = getDistance(point, particle); 

            if (d <= this.blackhole) {
                isClose = true;

                if (d <= distance || distance === null) {
                    distance = d;
                }

            }  

        }

        if (isClose){
            if (particle.radius < (this.dim * 0.0085)) {
                particle.radius += 0.25;
            }
            if (particle.green >= 0 && particle.blue >= 0) {
                particle.green -= 10;
                particle.blue -= 10;
            }           
        } else {
            if (particle.radius > particle.initialRadius) {
                particle.radius -= 0.25;
            }
            if (particle.green <= 255 && particle.blue <= 255) {
                particle.green += 10;
                particle.blue += 10;
            }           
        }

    },
    reverseBlackhole : function(particle, pIndex, particles){

        for (var i = 0; i < this.touches.length; i++) {

            var t = this.touches[i];

            var point = {
                x : t.clientX,
                y : t.clientY
            } 

            var distance = getDistance(point, particle);

            if (distance <= this.blackhole){

                var diff = getPointsDifference(point, particle);

                particle.vx += -diff.x / distance;
                particle.vy += -diff.y / distance;
            }

        }
    }
}

此外,如果有人想知道我有3个画布层,我会添加粒子渲染功能和清除功能的所有画布层
1.绘制全屏放射状渐变和粒子的背景
1.菜单画布
1.菜单按钮覆盖选择器(显示激活的菜单等)

Jarvis.prototype.backgroundDraw = function() {

    // particles

    var that = this;

    this.logoParticles.forEach(function(particle, i){

        particle.draw(that.backgroundCtx);

        that.logoParticles.motion.forEach(function(motionType, motionIndex){
            that.motion[motionType].call(that, particle, i, that.logoParticles, "foregroundParticles");
        });
        that.logoParticles.fx.forEach(function(fxType, fxIndex){
            that.fx[fxType].call(that, particle, i, that.logoParticles, "foregroundParticles");
        });
        that.logoParticles.collision.forEach(function(collisionType, collisionIndex){
            that.collision[collisionType].call(that, particle, i, that.logoParticles, "foregroundParticles");
        });
    });

    this.backgroundParticles.forEach(function(particle, i){

        particle.draw(that.backgroundCtx);

        that.backgroundParticles.motion.forEach(function(motionType, motionIndex){
            that.motion[motionType].call(that, particle, i, that.backgroundParticles, "backgroundParticles");
        });
        that.backgroundParticles.fx.forEach(function(fxType, fxIndex){
            that.fx[fxType].call(that, particle, i, that.backgroundParticles, "backgroundParticles");
        });
        that.backgroundParticles.collision.forEach(function(collisionType, collisionIndex){
            that.collision[collisionType].call(that, particle, i, that.backgroundParticles, "backgroundParticles");
        });
    });

}

Jarvis.prototype.clearCanvas = function() {

    switch(this.background.type){
        case "radial_gradient":
            this.setBackgroundRadialGradient(this.background.color1, this.background.color2);
            break;
        case "plane_color":
            this.setBackgroundColor(this.background.red, this.background.green, this.background.blue, this.background.opacity);
            break;
        default:
            this.setBackgroundColor(142, 214, 255, 1);
    }

    this.foregroundCtx.clearRect(this.clearStartX, this.clearStartY, this.clearDistance, this.clearDistance);
    this.middlegroundCtx.clearRect(this.clearStartX, this.clearStartY, this.clearDistance, this.clearDistance);
}

Jarvis.prototype.mainLoop = function() {
    this.clearCanvas();
    this.backgroundDraw();
    this.drawMenu();
    window.requestAnimFrame(this.mainLoop.bind(this));
}

任何其他的优化技巧将非常感谢。我已经读了一些文章,但我不知道如何进一步优化这段代码。

mlnl4t2r

mlnl4t2r1#

您可以使用FabricJS Canvas Library,FabricJS默认支持交互性,当您创建一个新对象(圆形,矩形等)时,您可以通过鼠标或触摸屏操作它。

var canvas = new fabric.Canvas('c');
var rect = new fabric.Rect({
    width: 10, height: 20,
    left: 100, top: 100,
    fill: 'yellow',
    angle: 30
});

canvas.add(rect);

看,我们用面向对象的方式工作。

suzh9iv8

suzh9iv82#

如果您希望加快代码的速度,这里有一些微优化:

  • for(var i = 0, l = bla.length; i < l; i++) { ... }而不是bla.forEach(...)
  • 减少回调使用。内联简单的东西。
  • 由于SQRT的原因,与距离进行比较的速度较慢。radius <= distance较慢,radius*radius <= distanceSquared较快。
  • 计算距离是通过计算差值来完成的。现在你要做两个函数调用,首先得到距离,然后得到差值。这里有一个小的重写:没有函数调用,没有不必要的计算。
reverseBlackhole : function(particle, pIndex, particles)
{
    var blackholeSqr = this.blackhole * this.blackhole,
        touches = this.touches,
        fnSqrt = Math.sqrt,
        t, diffX, diffY, dstSqr;
    for (var i = 0, l = touches.length; i < l; i++) {
        t = touches[i];
        diffX = particle.x - t.clientX;
        diffY = particle.y - t.clientY;
        distSqr = (diffX * diffX + diffY * diffY);
        // comparing distance without a SQRT needed
        if (dstSqr <= blackholeSqr){
            var dist = Math.sqrt(dstSqr); 
            particle.vx -= diffX / dist;
            particle.vy -= diffY / dist;
        }
    }
}

要加快绘图速度(或减少绘图过程中的滞后):

  • 将计算与图形分开
  • 仅在更新计算后请求重画

对于整个动画:

  • this.backgroundParticles.forEach(..):如果有200个粒子,则可以
  • 200个微粒次数(this.backgroundParticles.forEach(
  • 200个微粒(that.backgroundParticles.motion.forEach
  • 200个微粒(that.backgroundParticles.fx.forEach
  • 200个微粒(that.backgroundParticles.collision.forEach
  • 对于this.foregroundparticles.forEach(..)也是如此
  • 假设我们有200个背景和100个前景,也就是(2002003)+(1001003)个回调,也就是说每个节拍有150000个回调,我们还没有计算任何东西,也没有显示任何东西。
  • 以60 fps的速度运行它,每秒可以回调900万次。我想你可以在这里发现一个问题。
  • 也不要在那些函数调用中传递字符串。

为了获得更好的性能,去掉OOP的东西,只在有意义的地方使用难看的意大利面条代码。
碰撞检测可以通过不对每个粒子进行相互测试来优化。只需查找四叉树。实现起来并不困难,它的基础可以用来提出一个自定义的解决方案。
既然你正在做相当多的矢量数学,那就试试glmatrix library。优化的矢量数学:-)

g9icjywg

g9icjywg3#

我不知道除了切换到使用硬件加速的技术之外,您还可以在这里做什么主要的改进。
我希望这能帮上点忙,虽然正如问题评论中所说的那样WebGL会更快。如果你不知道从哪里开始,这里有一个很好的:韦伯格勒学院
但我还是看到了一些小东西:

radialWave : function(particle, pIndex, particles){

        // As you don't use distance here remove this line
        // it's a really greedy calculus that involves square root
        // always avoid if you don't have to use it

        // var distance = getDistance(particle, this.center);

        if (particle.radius >= (this.dim * 0.0085)) {
            particle.radiusOper = -0.02;
        } else if (particle.radius <= 1) {
            particle.radiusOper = 0.02;
        }

        particle.radius += particle.radiusOper * particle.radius;
    },

另一个小东西:

Jarvis.prototype.backgroundDraw = function() {

    // particles

    var that = this;

    // Declare callbacks outside of forEach calls
    // it will save you a function declaration each time you loop

    // Do this for logo particles
    var logoMotionCallback = function(motionType, motionIndex){
        // Another improvement may be to use a direct function that does not use 'this'
        // and instead pass this with a parameter called currentParticle for example
        // call and apply are known to be pretty heavy -> see if you can avoid this
        that.motion[motionType].call(that, particle, i, that.logoParticles, "foregroundParticles");
    };

    var logoFxCallback = function(fxType, fxIndex){
        that.fx[fxType].call(that, particle, i, that.logoParticles, "foregroundParticles");
    };

    var logoCollisionCallback = function(collisionType, collisionIndex){
        that.collision[collisionType].call(that, particle, i, that.logoParticles, "foregroundParticles");
    };

    this.logoParticles.forEach(function(particle, i){

        particle.draw(that.backgroundCtx);

        that.logoParticles.motion.forEach(motionCallback);
        that.logoParticles.fx.forEach(fxCallback);
        that.logoParticles.collision.forEach(collisionCallback);
    });

    // Now do the same for background particles
    var bgMotionCallback = function(motionType, motionIndex){
            that.motion[motionType].call(that, particle, i, that.backgroundParticles, "backgroundParticles");
    };

    var bgFxCallback = function(fxType, fxIndex){
        that.fx[fxType].call(that, particle, i, that.backgroundParticles, "backgroundParticles");
    };

    var bgCollisionCallback = function(collisionType, collisionIndex){
        that.collision[collisionType].call(that, particle, i, that.backgroundParticles, "backgroundParticles");
    };

    this.backgroundParticles.forEach(function(particle, i){

        particle.draw(that.backgroundCtx);

        that.backgroundParticles.motion.forEach(bgMotionCallback);
        that.backgroundParticles.fx.forEach(bgFxCallback);
        that.backgroundParticles.collision.forEach(bgCollisionCallback);
    });

}
omjgkv6w

omjgkv6w4#

我想您可能会发现Webworker支持与WebGL支持差不多:
WebGL支持:http://caniuse.com/#search=webgl
网络工作者支持:http://caniuse.com/#search=webworker
从表面上看,它们可能看起来不同,但实际上并非如此。你唯一能得到的是暂时支持IE10。IE11在市场份额上已经超过了IE10,而且差距还会继续扩大。唯一需要注意的是,webgl支持似乎也是基于更新的显卡驱动程序。
当然,我不知道你的具体需求,所以也许这不工作。

选项

等等什么?屏幕上显示200个项目很慢吗?

减少在画布上的工作量,在WebGL上做一些很酷的事情

许多库都是这样做的。画布应该是可用的,只是有点酷。WebGL一般都有所有很酷的粒子特性。

网络工作者

您可能需要使用一个延迟库,或者创建一个系统,该系统可以计算出所有Web工作者何时完成并拥有一个工作者线程池。
一些警告:
1.您不能从主应用程序访问任何内容,必须通过事件进行通信
1.通过Webworker传递的对象将被复制而非共享
1.在没有单独脚本的情况下设置Webworker可能需要一些研究
未经证实的传闻:我听说你可以通过网络工作者消息传递的数据量是有限的,你应该测试一下,因为它似乎直接适用于你的用例。

相关问题