【发布时间】:2014-05-02 12:06:31
【问题描述】:
我有一个简短的代码,可以在这些轨道上绘制圆(轨道)点(卫星)。卫星围绕轨道运行。事实上代码不是我的,但我被要求解决问题。
根据 chrome 和 firefox 中的分析器,函数 drawSatellite 占用 50%-100% cpu,我想知道为什么。
画布与您的窗口一样大 (1920x1080)。大约有160个轨道(随着时间的增加页面在线)。
这是drawSatellite:
OrbitBackground.prototype.drawSatellite = function(ctx, satellite) {
ctx.fillStyle = satellite.satellite.fill;
ctx.beginPath();
if (++satellite.satellite.angularPosition == 360)
satellite.satellite.angularPosition = 0;
// 1 FPS = 60 calls => 180 / 6 (6-times faster @ 60 FPS) = 30
var radians = satellite.satellite.angularPosition * Math.PI / 30 / satellite.rps;
if (satellite.backward)
radians = -radians;
ctx.arc(
satellite.satellite.x + satellite.orbit.radius * Math.cos(radians),
satellite.satellite.y + satellite.orbit.radius * Math.sin(radians),
satellite.satellite.radius,
0,
Math.PI*2,
true
);
ctx.closePath();
ctx.fill();
};
调用它的函数:
OrbitBackground.prototype.drawFrame = function() {
if (this.running)
requestAnimationFrame(this.drawFrame.bind(this));
this.dynamicStageCtx.clearRect(0, 0, this.pageWidth, this.pageHeight);
for (var i=0; i < this.orbits.length; i++) {
this.drawSatellite(this.dynamicStageCtx, this.orbits[i]);
}
};
【问题讨论】:
-
我认为问题可能是,我们将画布用作 2D 上下文,并且我们使用 javascript 函数而不是着色器,因此操作可能太繁重,因为 cpu 无法调用所有这些 javascript 函数每一帧?但这只是一个理论......
-
您的 FPS 是否太低?高 CPU 消耗并不总是意味着代码很慢或不是最优的。您应该关心的主要事情是您的绘图方法运行速度快于 (1000/targetFPS) 毫秒
-
在 chrome 中 fps 还可以,在 firefox 中 fps 非常低,有时浏览器会死机。在嵌入式系统上,fps 超低。
-
1) 缓存:satellite.satellite可以缓存避免6次访问,satellite.orbit.radius也可以缓存。 2) 什么是填充物?使填充正常化对表演有好处:创建填充后,执行 ctx.fillStyle = myFill;然后 myFill = ctx.fillStyle;所以填充是完全正确的格式。 3)尝试使用fillRect,看看画圆是否不是瓶颈。 4) 请注意,FF 和 Ch 都有画布调试/分析工具。
-
嗯,我尝试了 2 个样本。 this one seems to run faster in FF than Chrome。 This one is faster in Chrome than FF 至少在我的机器上
标签: javascript canvas webgl