Canvas gradient performance

前端 未结 1 689
天命终不由人
天命终不由人 2021-01-14 18:17

I am currently programming a little game using canvas. For the game I need some kind of fog which hides the most part of the map and only a small area around the player shou

1条回答
  •  迷失自我
    2021-01-14 18:37

    Cache the gradient to an off-screen canvas then draw in the canvas with drawImage() instead:

    • Create an off-screen canvas the size of the fog
    • Draw in the gradient
    • Use off-screen canvas as an image when you need the fog.

    This way the processing creating and calculating the gradient is eliminated. Drawing an image is basically a copy operation (there is a little bit more, but performance is very good).

    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;
    }
    

    Now you can simply draw in the canvas returned from the above function instead of creating the gradient every time:

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

    0 讨论(0)
提交回复
热议问题