gpt4 book ai didi

绘制多个对象时 Javascript 性能下降

转载 作者:行者123 更新时间:2023-11-30 14:40:05 25 4
gpt4 key购买 nike

我创建了一个 Canvas ,我在其中绘制了 100 个立方体,每个立方体具有不同的速度、位置和大小。它以我想要的帧速率运行,正如我所期望的那样。

但是当我切换到不同的程序时,我的笔记本电脑需要几秒钟来调整,所以我有几秒钟无法使用任何程序,我认为这可能是因为脚本和当我采取查看任务管理器,我的 GPU 使用率上升到 40%

代码如下:

  var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

var w = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
var h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);

c.setAttribute('width', w);
c.setAttribute('height', h);

var Ypos = [];
var Xpos = [];
var cubeWidth = [];
var Yspeed = [];
for (var i = 0; i < 100; i ++) cubeWidth[i] = getRandomInt(7, 10);
for (var i = 0; i < 100; i ++) Yspeed[i] = getRandomInt(30, 90) / 10;
for (var i = 0; i < 100; i ++) Ypos[i] = getRandomInt(0, c.height);
for (var i = 0; i < 100; i ++) Xpos[i] = getRandomInt(0, c.width);

setInterval( function() {
ctx.clearRect(0, 0, c.width, c.height);

for (var i = 0; i < 100; i ++) {
Ypos[i] += Yspeed[i];

if (Ypos[i] + cubeWidth[i] / 2 > h) {
Ypos[i] = -cubeWidth[i] / 2;
Xpos[i] = getRandomInt(0, c.width);
}

var width = 10;
var height = 10;

ctx.beginPath();
ctx.moveTo(-cubeWidth[i] / 2 + Xpos[i], -cubeWidth[i] / 2 + Ypos[i]);
ctx.lineTo(cubeWidth[i] / 2 + Xpos[i], -cubeWidth[i] / 2 + Ypos[i]);
ctx.lineTo(cubeWidth[i] / 2 + Xpos[i], cubeWidth[i] / 2 + Ypos[i]);
ctx.lineTo(-cubeWidth[i] / 2 + Xpos[i], cubeWidth[i] / 2 + Ypos[i]);
ctx.lineTo(-cubeWidth[i] / 2 + Xpos[i], -cubeWidth[i] / 2 + Ypos[i]);
ctx.stroke();
ctx.closePath();
}
}, 1000/60);

function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}

我该怎么做才能解决这个问题?

最佳答案

摆脱 setInterval() 因为这肯定会导致问题并要求浏览器保持事件状态,即使操作系统正在尝试做其他事情。将绘图包装在它自己的函数中,并在完成后使该函数调用自身,但使用 requestAnimationFrame() 以便它仅在窗口处于事件状态时绘制...

function() draw {
ctx.clearRect(0, 0, c.width, c.height);

for (var i = 0; i < 100; i ++) {
Ypos[i] += Yspeed[i];

if (Ypos[i] + cubeWidth[i] / 2 > h) {
Ypos[i] = -cubeWidth[i] / 2;
Xpos[i] = getRandomInt(0, c.width);
}

var width = 10;
var height = 10;

ctx.beginPath();
ctx.moveTo(-cubeWidth[i] / 2 + Xpos[i], -cubeWidth[i] / 2 + Ypos[i]);
ctx.lineTo(cubeWidth[i] / 2 + Xpos[i], -cubeWidth[i] / 2 + Ypos[i]);
ctx.lineTo(cubeWidth[i] / 2 + Xpos[i], cubeWidth[i] / 2 + Ypos[i]);
ctx.lineTo(-cubeWidth[i] / 2 + Xpos[i], cubeWidth[i] / 2 + Ypos[i]);
ctx.lineTo(-cubeWidth[i] / 2 + Xpos[i], -cubeWidth[i] / 2 + Ypos[i]);
ctx.stroke();
ctx.closePath();
}

setTimeout(function() {
window.requestAnimationFrame(draw);
}, 1000 / 60);
}

// start the animation
draw();

您可以在此处找到有关 requestAnimationFrame() 的更多信息...

https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame

关于绘制多个对象时 Javascript 性能下降,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49817456/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com