Canvas gradient performance

淺唱寂寞╮ 提交于 2019-12-01 09:16:28

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