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.
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.
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:
The result (shown on a black page):
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With