【问题标题】:How to make the black part of the background image transparent?如何使背景图像的黑色部分透明?
【发布时间】:2016-07-05 18:18:14
【问题描述】:

这是我想要实现的结果。如图所示,二维码由黑色和白色组成,但我希望黑色部分是透明的,以便与外面的背景融为一体。外面的背景可能会改变,它并不总是绿色的。

我尝试过这样的 CSS 使用背景混合模式:

 background-image: url('');
 background-color: rgba(0,0,0,0);
 background-blend-mode: screen;

什么都不做。

谢谢帮助。

【问题讨论】:

  • 将二维码转换为透明PNG。其中黑色值的 alpha 值为 0。

标签: javascript css


【解决方案1】:

您实际上可以通过canvas pixel manipulation 实现此效果,但正如其他用户所说,通过图像编辑程序使您的图像透明会更简单。

我在fiddle here 中创建了一个如何实现此目的的示例。

这段代码首先检索图像元素<img id="code" src="url.png">,构造一个画布对象并通过context.drawImage调用将图像的内容绘制到画布中。

// Get the image element.
var el = document.getElementById('code');

// Create a canvas and set its width and height.
var canvas = document.createElement('canvas');
canvas.setAttribute('width', 250);
canvas.setAttribute('height', 250);

// Get the canvas drawing context, and draw the image to it.
var context = canvas.getContext('2d');
context.drawImage(el, 0, 0, canvas.width, canvas.height);

接下来,

// Get the canvas image data.
var imageData = context.getImageData(0, 0, canvas.width, canvas.height);

// Create a function for preserving a specified colour.
var preserveColor = function(imageData, color) {
    // Get the pixel data from the source.
    var data = imageData.data;
    // Iterate through all the pixels.
    for (var i = 0; i < data.length; i += 4) {
        // Check if the current pixel should have preserved transparency. This simply compares whether the color we passed in is equivalent to our pixel data.
        var preserve = data[i] === color.r
            && data[i + 1] === color.g
            && data[i + 2] === color.b
            && data[i + 3] === color.a;

        // Either preserve the initial transparency or set the transparency to 0.
        data[i + 3] = preserve ? data[i + 3] : 0;
    }
    return imageData;
};

// Get the new pixel data and set it to the canvas context.
var newData = preserveColor(imageData, {r: 255, g: 255, b: 255, a: 255});
context.putImageData(newData, 0, 0);

最后,我们使用document.body.appendChild(canvas); 将元素添加到我们的页面。您也可以用画布完全替换原始图像元素。

显然,这不是一个理想的解决方案,因为迭代像素数据可能非常缓慢,并且只会随着图像尺寸的增大而增加。您还可以轻松地更改 preserveColor 函数,改为使用 makeTransparent 执行相反的操作,其中指定的颜色变为透明。但是,对于与您指定的颜色相似的颜色,这将需要更多的逻辑。或者,您可以将其实现为着色器,以便通过将其转移到 GPU 而不是 CPU 来提高处理效率。

【讨论】:

    【解决方案2】:

    你有正确的混合模式,我假设背景图像 url 被故意省略,所以我求助的第一个原因是浏览器兼容性。例如,请查看compatibility chart on caniuse.com

    我建议在这里使用透明 PNG,因为这正是它的目的。即使你让background-blend-mode 工作,除非背景完全是黑色(意思是#000)——看你的示例图像,情况并非如此,所以你不会得到你想要的效果。 .

    我在这里能想到的另一个问题是,您可能想要img 元素中的二维码,原因如下:

    • 用户可能希望以预期的方式保存图像
    • 背景图片不会呈现为块元素,因此根据您的布局,它们可能很容易重叠
    • 背景图片在打印页面时经常被丢弃,因此不应将它们用于内容
    • 屏幕阅读器可能会忽略背景图片,假设它们只是设计图

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-06
      • 1970-01-01
      • 2017-10-13
      • 2023-03-15
      • 2022-01-17
      • 1970-01-01
      • 2016-02-22
      • 2012-06-26
      相关资源
      最近更新 更多