您实际上可以通过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 来提高处理效率。