In the development, I encountered a need to set a transparent color. The description is probably a picture, and then give a color, and set all the pixels of this color on the picture to a transparent color, as shown below.
The implementation idea is to draw the picture on the canvas, then traverse the pixel information of the picture, and set the alpha of the specified rgb to 0, that is, set it to full transparency.
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
const img = new Image();
img.crossOrigin = 'Anonymous';
img.src = src;
img.onload = () => {
const w = img.width;
const h = img.height;
context.drawImage(img, 0, 0);
const imgData = context.getImageData(0, 0, w, h);
const pixcount = w * h;
for (let i = 0; i < pixcount * 4; i += 4) {
const r = imgData.data[i];
const g = imgData.data[i + 1];
const b = imgData.data[i + 2];
if (
Math.abs(r - color.r) <= dis &&
Math.abs(g - color.g) <= dis &&
Math.abs(b - color.b) <= dis
) {
imgData.data[i + 3] = 0;
}
}
// 转成base64
canvas.toDataURL('image/webp')
}
Several problems were found during the implementation of this feature:
1. canvas.toDataURL(type, encoderOptions)
The image format type defaults to image/png,
The encoderOptions image quality defaults to 0.92, but this parameter does not take effect when the type is image/png, only in
Valid in image/jpeg and image/webp formats
2. In the process of using this method, it is found that the original image jpeg is only 1M. After setting the transparent color, when the image format is png, the image size increases to 10M🤯🤯,
In order to solve this problem, the following attempts were made:
Scaling the canvas, the export is still the original canvas size, and the picture is still 10M, this solution does not work 🙅♂️
Set to jpeg format, transparent pixels will be lost, transparent pixels will become black, I was so stupid at that time, how can jpeg have transparent pixels 😅
Set to image/webp format, the image volume is 900K, perfect 😊, but please note that this type is not supported on Safari, on safari canvas.toDataURL('image/webp') will default to canvas.toDataURL('image/ png')
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。