Erik
Erik

Reputation: 42

transparency to a single image within the canvas

I am trying to give transparency to a single image that I have created on the canvas, globalAlpha does not work for me because I need to only affect one image and that affects all images.

var canvas = document.getElementById('cvs');
var ctx = canvas.getContext('2d');
var image = new Image();
image.src = "../img/image.jpg";
image.onload = function () {
    ctx.drawImage(image, 200, 200, 100, 100);
}

var image1 = new Image();
image1.src = "../img/image.jpg";
image1.onload = function () {
    ctx.drawImage(image1, 400, 400, 100, 100);
}

Upvotes: 0

Views: 100

Answers (2)

Jannchie
Jannchie

Reputation: 1008

You can set the ctx global alpha around render.

image1.onload = function () {
    // Save the original alpha
    ctx.save();
    // Set global alpha
    ctx.globalAlpha = 0.5;
    // Draw
    ctx.drawImage(image1, 400, 400, 100, 100);
    // Restore the original alpha
    ctx.restore();
}

Upvotes: 0

Randy Casburn
Randy Casburn

Reputation: 14165

Set globalAlpha to your transparency level, draw the image, return globalAlpha to 1.

Upvotes: 1

Related Questions