仅使用CSS,我是否只能使用PNG的alpha通道?

jed*_*mao 4 css png transparency webkit alpha

我有这个具有可变透明度的红色PNG图像,但我需要在网页上将其显示为具有可变透明度的白色.我想这只有两种方法可行:

  • 将背景颜色设置为白色,但不知何故使用PNG的alpha通道来设置其透明度.
  • 以某种方式使PNG去饱和或将其调色板更改为仅白色.

我只允许使用CSS来实现这个目标; 否则,我会考虑其他选择.

编辑:我只需要在Safari(webkit)中工作.对不起我以前没有提过这个.

Lit*_*tek 6

要求回答:

-webkit-mask 可以拍摄图像并使用它的alpha通道作为遮罩(非常像photoshop遮罩)

div {
  background:white;
  -webkit-mask:url(url/to/image.png);
}
Run Code Online (Sandbox Code Playgroud)

小提琴

但我同意所有建议画布的答案 - 我知道你只限于纯粹的CSS,但画布是一种方式去这里.


Phr*_*ogz 5

不,您不能仅使用CSS以跨浏览器方式执行此操作.

(然而,使用HTML5 Canvas和你的图像来做这件事会很容易.)

画布解决方案:

您可以在此处查看此示例: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';
Run Code Online (Sandbox Code Playgroud)

正在使用alpha 的源图像:
一个带有几个孔和透明阴影的圆球
结果(黑色页面上显示):
在黑背景的白色剪影

这里的关键是使用destination-in合成模式使用源图像的不透明度作为结果,同时保持原始颜色(在这种情况下为白色)完整.