Canvas Gradient Efficiency

I am currently programming a small game using canvas. For the game I need some kind of fog that hides most of the map, and only a small area around the player should be visible. Therfor I use the second canvas to overlay the one where the game takes place and fill it with a gradient (from transparent to black):

function drawFog(){
fogc.clearRect(0,0,700,600);
// Create gradient
var grd=fogc.createRadialGradient(player.getPosX(),player.getPosY(),0,player.getPosX(),player.getPosY(),100);
grd.addColorStop(0,"rgba(50,50,50,0)");
grd.addColorStop(1,"black");

// Fill with gradient
fogc.fillStyle=grd;
fogc.fillRect(0,0,700,600);
}

Unfortunately, this causes huge performance problems, as it will be redrawn for each frame.

I wanted to ask if there could be a better solution to achieve the same effect with better performance.

+3
source share
1 answer

Adjust the gradient to the screen canvas, and then draw the canvas using drawImage ():

  • , .

, . - ( , ).

function createFog(player) {

    // Create off-screen canvas and gradient
    var fogCanvas = document.createElement('canvas'),
        ctx = fogCanvas.getContext('2d'),
        grd = fogc.createRadialGradient(player.getPosX(),
                                        player.getPosY(),
                                        0,player.getPosX(),
                                        player.getPosY(),100);

    fogCanvas.width = 700;
    fogCanvas.height = 700;

    grd.addColorStop(0,"rgba(50,50,50,0)");
    grd.addColorStop(1,"black");

    // Fill with gradient
    ctx.fillStyle = grd;
    ctx.fillRect(0,0,700,600);

    return fogCanvas;
}

, , , :

var fog = createFog(player);
ctx.drawImage(fog, x, y);
+7

All Articles