簡體   English   中英

如何提高javascript畫布模式的性能

[英]How to improve javascript canvas pattern performance

我正在使用畫布創建一個 2D html5 游戲。 我目前正在制作非常大的地圖(25000 像素 x 25000 像素)。 我現在正在嘗試將紋理添加到地圖形狀

這是代碼:

let snowPattern;
let sandPattern;
let junglePattern;

const jungleTexture = new Image();
jungleTexture.src = "./assets/game/map/jungleTexture.png";

jungleTexture.onload = function() {
    junglePattern = ctx.createPattern(jungleTexture, "repeat");
};


const snowTexture = new Image();
snowTexture.src = "./assets/game/map/snowTexture.png";

snowTexture.onload = function() {
    snowPattern = ctx.createPattern(snowTexture, "repeat");
};


const sandTexture = new Image();
sandTexture.src = "./assets/game/map/sandTexture.png";

sandTexture.onload = function() {
    sandPattern = ctx.createPattern(sandTexture, "repeat");
};



//Function to draw map shapes
function animate() {

    mapX = document.documentElement.clientWidth / 2 - camera.x * zoom;
    mapY = document.documentElement.clientHeight / 2 - camera.y * zoom;


    ctx.setTransform(1, 0, 0, 1, mapX, mapY);

    //Arctic
    if (document.getElementById("3").checked === true) {
        ctx.fillStyle = snowPattern;
    }

    else {
        ctx.fillStyle = "#EFF4F6";
    }

    ctx.fillRect(0, 0, 12500 * zoom, 12500 * zoom);



    //Desert

    if (document.getElementById("3").checked === true) {
        ctx.fillStyle = sandPattern;
    }

    else {
        ctx.fillStyle = "#E5C068";
    }

    ctx.fillRect(12499 * zoom, 0 * zoom, 12500 * zoom, 12500 * zoom);



    //Jungle

    if (document.getElementById("3").checked === true) {
        ctx.fillStyle = junglePattern;
    }

    else {
        ctx.fillStyle = "#0F7F2A";
    }

    ctx.fillRect(0, 12500 * zoom, 25000 * zoom, 12500 * zoom);

    window.requestAnimationFrame(animate);
}

animate();

因此,當我只在形狀的背景上添加顏色時,它運行良好(一致 144 fps),但是使用圖案時,我的 fps 會降低到 20。

有沒有人知道我如何提高性能?

您正在嘗試繪制一個巨大的矩形,它會產生預期的開銷。 這取決於瀏覽器,但畫布有一些限制。 當您達到這些限制時,您將遭受性能或崩潰。 您可以在此處查看限制 此外,繪制一個巨大的矩形總是會以性能不佳而告終。

我的建議是:繪制一個較小的矩形(可能比您的游戲屏幕大一點)並將其移動到矩形的末端,就在圖案結束之前,再次將其移回。

最后,問題不是來自大小,即使是 50px x 50px 像素矩形,性能也很糟糕。 您需要使用 ctx.beginPath()、ctx.rect、ctx.closePath() 和 ctx.fill() 才能獲得正常的性能。

暫無
暫無

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

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