首页 文章

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

提问于
浏览
4

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

  • 将背景颜色设置为白色,但不知何故使用PNG的Alpha通道设置其透明度 .

  • 以某种方式使PNG去饱和或将其调色板更改为仅白色 .

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

Edit :我只需要在Safari(webkit)中使用它 . 对不起我以前没有提过这个 .

3 回答

  • 3

    要求回答:

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

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

    Fiddle

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

  • 6

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

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

    Canvas Solution

    你可以在这里查看这个例子: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';
    

    正在使用其alpha的source image

    A round ball with a couple holes and transparent shadow

    result(显示在黑页上):

    white silhouette on black background

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

  • 5

    在小于9的IE版本中,有chroma filter,这样做 . 在其他浏览器中,你运气不好 .

    你可以使用canvas标签和一些javascript来获得相同的效果,但那不是CSS .

相关问题