jedmao
jedmao

Reputation: 10502

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:

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.

Upvotes: 4

Views: 5675

Answers (3)

Litek
Litek

Reputation: 4888

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.

Upvotes: 7

Phrogz
Phrogz

Reputation: 303254

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.

Upvotes: 5

Rich Bradshaw
Rich Bradshaw

Reputation: 72965

In IE versions less than 9 there is the chroma filter, which does this. In other browsers, you are out of luck.

You could use the canvas tag with some javascript to get the same effect, but that isn't CSS.

Upvotes: 3

Related Questions