Javascript 优化画布多对象渲染

Javascript 优化画布多对象渲染,javascript,html,canvas,rendering,pixi.js,Javascript,Html,Canvas,Rendering,Pixi.js,我正在尝试制作一个ants模拟器,我使用基本的Javascript画布渲染器 以下是渲染代码的一部分: render(simulation) { let ctx = this.ctx; // Clear previous frame ctx.clearRect(0, 0, canvas.width, canvas.height); // Pheromones let pheromone; let pherom

我正在尝试制作一个ants模拟器,我使用基本的Javascript画布渲染器

以下是渲染代码的一部分:

render(simulation) {
    
    let ctx = this.ctx;
    
    // Clear previous frame
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    
    
    // Pheromones
    let pheromone;
    let pheromoneXPos;
    let pheromoneYPos;
    for (let i = 0; i < simulation.pheromones.length; i++) {
      pheromone = simulation.pheromones[i];
      pheromoneXPos = pheromone.position[0];
      pheromoneYPos = pheromone.position[1];
      ctx.fillRect(pheromoneXPos, pheromoneYPos, 1, 1);
    }
    
    
    // ... rendering other stuff
    
}
渲染(模拟){
设ctx=this.ctx;
//清除上一帧
clearRect(0,0,canvas.width,canvas.height);
//信息素
让信息素;
让信息素释放;
释放信息素;
for(设i=0;i
下面是一个示例(它运行平稳,因为我使用的对象减少了约90%:

simulation.pheromones.length
非常大(~25000),渲染一帧所需的时间太长(在我的计算机上为250ms)
我应该怎么做才能使它渲染得更快?我应该使用渲染引擎(比如PixiJS)吗?还是我用错了


注意:大多数对象(信息素)与前一帧相同(它们每秒只更新一次或两次)。

由于所有矩形的样式似乎都相同,因此可以将所有这些矩形组合在一个子路径中,并使用此更复杂的子路径仅调用一次
fill()

const canvas=document.querySelector(“canvas”);
常数w=canvas.width=500;
常数h=canvas.height=500;
const ctx=canvas.getContext(“2d”);
常量生成信息素=()=>({
x:w/2,
y:h/2,
dx:Math.random()*20-10,
dy:Math.random()*20-10
});
const信息素=数组。from({length:50000},makePheromone);
ctx.fillStyle=“红色”;
请求动画帧(绘制);
函数绘图(){
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.beginPath();
信息素。forEach((obj)=>{
obj.x+=obj.dx;
如果(对象x<0){
对象x+=w;
}
否则如果(对象x>w){
对象x-=w;
}
对象y+=对象dy;
如果(对象y<0){
对象y+=h;
}
否则如果(对象y>h){
对象y-=h;
}
ctx.rect(对象x,对象y,1,1);
});
ctx.fill();
请求动画帧(绘制);
}

Hi@kaido,谢谢你的详细回答,我尝试了你的建议,做了一些修改,并将所有的
信息素存储在
uint8clampedaray
上,然后将缓冲区设置为
ImageData
,效果非常好。现在我只需要让它们随着时间的推移而失去强度(alpha),有没有一种方法可以对
uint8clampedaray
应用不透明度过滤器,而不必遍历每个像素?不是真的,但我很惊讶这是您选择的解决方案。你能澄清一下你的具体情况吗:这些是动画的,有不同的颜色,每个信息素都有自己的阿尔法还是全局的?信息素只是静态的点(两种类型:绿色和蓝色),随着时间的推移而衰减,每次蚂蚁向前走一步,就会留下一个信息素,当它想找到回家的路时,它会跟着那些信息素的气味走。因此,我可以像对待图像一样对待它们,并随着时间的推移降低它们的不透明度。