Search code examples
javascriptperformancehtml5-canvastextures2d-games

How to improve javascript canvas pattern performance


I'm creating a 2D html5 game using canvas. I'm currently making the map who is very large (25000px x 25000px). I'm now trying to add textures to map shapes

Here is the code :

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();

So when I only put colors on the background of the shapes, it's working perfectly (constent 144fps), but with patterns, my fps decrease to 20.

Does anyone have an idea about how can I improve the performances ?


Solution

  • Finally, the problem wasnt coming from the size, even with a 50px x 50px pixel rect, the performance was terrible. You need to use ctx.beginPath(), ctx.rect, ctx.closePath() and ctx.fill() to get normal performances.