Home > Net >  How to improve javascript canvas pattern performance
How to improve javascript canvas pattern performance

Time:10-27

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 ?

CodePudding user response:

You are trying to draw a massive rectangle and it creates an overhead which is expected. It depends on the browser but canvas has some limits. When you reach those limits, you will suffer performance or crash. You can see the limits here Also drawing a huge rectangle will always end with poor performance.

My suggestion would be: draw a smaller rectangle (probably a bit bigger than your game screen) and move it till end of the rectangle and just before pattern ends, move it back again.

CodePudding user response:

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.

  • Related