简体   繁体   中英

Change opacity of URL image in canvas

I have a few lines of code that add a plant into my canvas game:

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

This puts the image into my game. However, I also want to make it faded out a bit. Could I use GlobalAlpha for this? And if so, how do I do it? Thanks.

Yes, globalAlpha is a good choice. It takes a value in the range [0, 1].

For example:

(example also corrects loading pattern)

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

You might want to consider a callback too as loading images happens asychronously, for example, a modified example with callback-ability could look like:

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

Then:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM