0

I'm trying to display an image via JavaScript and set its opacity, but the opacity I've specified is getting ignored. I've tried all the latest browsers, but am mainly using IE11. The image I specify displays fine and I can position, scale, and rotate it without any problem. I've done extensive searches on this site and others to try to identify the problem but so far haven't had any luck. I've also tried rebooting my PC and using another PC to check the results. Nothing seems to help. Even trying a PNG file.

Here's my code:

var imageObj = new Image();
imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg';
imageObj.onload = function () {
    imageObj.style.filter = "alpha(opacity=20)";
    imageObj.style.opacity = 0.20;

ctx.drawImage(imageObj, 10, 10);
};

Oh, prior to this code, the background color was set to pure white (#ffffff). I tried playing around with the background color, but it seemed to make no difference.

2 Answers2

0

Try context.imageSmoothingEnabled = true;. The canvas element has a global alpha attribute that lets you apply partial transparency to anything you draw. You can see more here.

Ringo
  • 3,795
  • 3
  • 22
  • 37
-1

The CSS opacity is applied to the Node and not to the image data, this means that when you draw to your canvas' context, this meta information is forgotten.

Instead, you can use context.globalAlpha

imageObj.onload = function () {
    var x = ctx.globalAlpha;
    ctx.globalAlpha = 0.2;
    ctx.drawImage(imageObj, 10, 10);
    ctx.globalAlpha = x;
};

Beware though, this may not be safe if you're expecting to draw a lot asynchronously, so you may even want to create a second canvas for fixing the alpha, then export/import into the canvas you're really interested in, getImageData, putImageData.

Another option could always be to use an image format which supports an alpha channel, such as PNG and just serve the images at the desired opacity. This would cut down on processing, but may increase bandwidth usage (really depends on the image contents to how well each format compresses the data, e.g. JPEG is designed for photos/real world images whereas a PNG may better compress an artificial image with no noise).

Paul S.
  • 64,864
  • 9
  • 122
  • 138
  • @downvoter, if the downvote is because I mention _PNG_, I mean have the _PNG_ image saved at `0.2` alpha and don't introduce alpha in the _JavaScript_, not just a 1:1 conversion. Otherwise, please comment so I am able to address the issue you have with this answer. – Paul S. Dec 27 '13 at 02:24
  • Thanks Paul, property globalAlpha was just what I was looking for. I'm very new at JavaScript and its graphics methods, so this transparency thing really stumped me. My goal is to draw an image that moves and fades out over time. The image can be from a JPEG or PNG file. – Don Peters Dec 28 '13 at 01:59
  • @DonPeters if the opacity isn't static then the image source doesn't matter as much. – Paul S. Dec 28 '13 at 12:02