Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using only CSS, can I use only the alpha channel of a PNG?

I have this red PNG image that has variable transparency, but I need to display it on the web page as white with variable transparency. I'm thinking there's only two ways this might work:

  • Set the background-color to white, but somehow use the alpha channel of the PNG to set its transparency.
  • Somehow de-saturate the PNG or change its color palette to only white.

I'm only allowed to use CSS to achieve this goal; otherwise, I'd look into other options.

Edit: I only need this to work in Safari (webkit). Sorry I didn't mention this before.

like image 871
jedmao Avatar asked Dec 07 '22 19:12

jedmao


2 Answers

Requested answer:

-webkit-mask can take an image and use it's alpha channel as mask (pretty much like photoshop mask)

div {
  background:white;
  -webkit-mask:url(url/to/image.png);
}

Fiddle

But I agree with all of the answers suggesting canvas - I know you're limited to pure css, but canvas is a way to go here.

like image 99
Litek Avatar answered Dec 11 '22 10:12

Litek


No, you cannot do this in a cross-browser manner using only CSS.

(It would be rather easy to do this using an HTML5 Canvas along with your image, however.)

Canvas Solution:

You can view this example live here: http://phrogz.net/tmp/canvas_png_alpha.html

var ctx = document.createElement('canvas').getContext('2d');
var img = new Image;
img.onload = function(){
  // Make the canvas the same size as the image
  var w = ctx.canvas.width  = img.width;
  var h = ctx.canvas.height = img.height;

  // Fill it with (fully-opaque) white
  ctx.fillStyle = '#fff'; ctx.fillRect(0,0,w,h);

  // Draw the image in a special blend mode that forces its opacity on the result
  ctx.globalCompositeOperation = 'destination-in';
  ctx.drawImage(img,0,0);

  // Set an image on the page to use this canvas data
  // The data URI can also be copy/pasted and used inline in HTML or CSS
  document.getElementById('result').src=ctx.canvas.toDataURL();
}

// Load the image to use _after_ setting the onload handler
img.src = 'alphaball.png';

The source image whose alpha is being used:
A round ball with a couple holes and transparent shadow
The result (shown on a black page):
white silhouette on black background

The key here is using the destination-in compositing mode to use the opacity of the source image as the result, while leaving the original colors (in this case white) intact.

like image 30
Phrogz Avatar answered Dec 11 '22 09:12

Phrogz