簡體   English   中英

提高子畫面繪制性能

[英]Improve sprite drawing performance

我有這個功能來繪制一個精靈對象(它只是一個像素值數組的對象):

this.draw = (ctx, x, y, scale) => {
    let i = 0;
    let startIndex, red, green, blue, alpha, currentX, currentY;
    while(i < this.size.width * this.size.height){
        startIndex = i * 4;
        red = this.pixArray[startIndex];
        green = this.pixArray[startIndex + 1];
        blue = this.pixArray[startIndex + 2];
        alpha = this.pixArray[startIndex + 3];
        // Draw, but not if the pixel is invisible
        if(alpha != 0){
            ctx.fillStyle = `rgba(${red}, " + ${green} + ", " + ${blue} + ", " + ${alpha / 255.0} + ")`;
            currentX = i % this.size.width;
            currentY = (i - currentX) / this.size.width;
            ctx.fillRect(Math.round(x + (currentX * scale)), Math.round(y + (currentY * scale)),
            Math.round(scale), Math.round(scale));
        }
        i++;
    }
}

唯一缺少的是pixArray ,它是像素值的Uint8Array。

但是,性能相當糟糕。 我發現某些性能因畫布更改狀態( ctx.fillStyle )而ctx.fillStyle ,但是我有必要在每次迭代中進行修改。 即使fillStyle保持不變,性能仍然不可接受。 我知道我可以選擇或預先渲染,但我希望避免這種情況。

使用ImageData將數組直接映射到臨時畫布,然后通過一次操作以適當的比例將其繪制到目標畫布:

const { width, height } = this.size;
const tCan = document.createElement('canvas');

// block scope to clean up temporary variables
{
  const tCtx = tCan.getContext('2d');
  const imgData = tCtx.createImageData(width, height);

  tCan.width = width;
  tCan.height = height;
  imgData.data.set(this.pixArray);
  tCtx.putImageData(imgData, 0, 0);
}

this.draw = (ctx, x, y, scale) => {
  ctx.drawImage(tCan, x, y, Math.round(width * scale), Math.round(height * scale));
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM