画布渐变性能 [英] Canvas gradient performance

查看:167
本文介绍了画布渐变性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用画布编程一个小游戏。对于游戏我需要一些雾,隐藏地图的大部分,只有一个小的区域周围的玩家应该是可见的。 Therfor我使用第二个画布来覆盖游戏发生的地方,并填充一个渐变(从透明到黑色):

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.

推荐答案

将渐变缓存到屏幕画布上,然后使用drawImage()在画布上绘制:

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


  • 创建除雾大小的屏幕画布

  • 在渐变中绘制

  • 使用离屏画布作为图片需要雾。

这样,消除了创建和计算渐变的处理。绘制图像基本上是一个复制操作(有一点点,但性能非常好)。

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

这篇关于画布渐变性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆