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';
3 回答
要求回答:
-webkit-mask可以拍摄图像并使用它的alpha通道作为遮罩(非常像photoshop遮罩)
Fiddle
但我同意所有建议画布的答案 - 我知道你只限于纯粹的CSS,但画布是一种方式去这里 .
不,您不能仅使用CSS以跨浏览器方式执行此操作 .
(然而,使用HTML5 Canvas和你的图像来做这件事会很容易 . )
Canvas Solution :
你可以在这里查看这个例子:http://phrogz.net/tmp/canvas_png_alpha.html
正在使用其alpha的source image:
result(显示在黑页上):
这里的关键是使用destination-in合成模式使用源图像的不透明度作为结果,同时保持原始颜色(在本例中为白色)完整 .
在小于9的IE版本中,有chroma filter,这样做 . 在其他浏览器中,你运气不好 .
你可以使用canvas标签和一些javascript来获得相同的效果,但那不是CSS .