Canvas gradient performance

断了今生、忘了曾经 提交于 2019-12-30 10:57:05

问题


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 should be visible. Therfor I use a 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);
}

Unfortunatly this is causing huge perfomance problems since it will be redrawn for every frame.

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


回答1:


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


来源:https://stackoverflow.com/questions/21877240/canvas-gradient-performance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!