在画布中更改URL图像的不透明度

时间:2015-05-06 01:08:45

标签: javascript html html5 canvas html5-canvas

我有几行代码将植物添加到我的画布游戏中:

function drawPlant() {
    base_image = new Image();
    base_image.src = 'http://i.imgur.com/xOupnQp.png';
    if (treeLoaded) {
        ctx.drawImage(base_image, 20, 333, 60, base_image.height * (60/base_image.width));
    }
    else {
    base_image.onload = function(){
        treeLoaded = true;
    };
}

这会将图像放入我的游戏中。但是,我也想让它淡出一点。我可以使用GlobalAlpha吗?如果是这样,我该怎么做?感谢。

1 个答案:

答案 0 :(得分:2)

是的,globalAlpha是个不错的选择。它取一个[0,1]范围内的值。

例如:

(例子也纠正了加载模式)

function drawPlant() {
    base_image = new Image();
    base_image.onload = function(){
        treeLoaded = true;
        ctx.globalAlpha = 0.5; // 50% opacity
        ctx.drawImage(this, 20, 333, 60, base_image.height * (60/base_image.width));
        ctx.globalAlpha = 1; // normal full opacity
    };
    base_image.src = 'http://i.imgur.com/xOupnQp.png';
}

您可能也想考虑回调,因为加载图像是异步发生的,例如,具有回调能力的修改示例可能如下所示:

function drawPlant(callback) {
    base_image = new Image();
    base_image.onload = function(){
        treeLoaded = true;
        ctx.globalAlpha = 0.5; // 50% opacity
        ctx.drawImage(this, 20, 333, 60, base_image.height * (60/base_image.width));
        ctx.globalAlpha = 1;  // normal full opacity
        callback(this);       // invoke callback with image as argument
    };
    base_image.src = 'http://i.imgur.com/xOupnQp.png';
}

然后:

drawPlant(function(img) {
    // continue from here...
});