我创建了一个示例,演示了如何在此处的fiddle中实现此目的。
这段代码首先获取图像元素<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上,从而使处理更有效率。