主要JS
/**清除图片背景颜色 **/
function removeImgBg(img) {//背景颜色 白色const rgba = [255, 255, 255, 255];// 容差大小const tolerance = 60;var imgData = null;const [r0, g0, b0, a0] = rgba;var r, g, b, a;const canvas = document.createElement('canvas');const context = canvas.getContext('2d');const w = img.width;const h = img.height;canvas.width = w;canvas.height = h;context.drawImage(img, 0, 0);imgData = context.getImageData(0, 0, w, h);for (let i = 0; i < imgData.data.length; i += 4) {r = imgData.data[i];g = imgData.data[i + 1];b = imgData.data[i + 2];a = imgData.data[i + 3];const t = Math.sqrt((r - r0) ** 2 + (g - g0) ** 2 + (b - b0) ** 2 + (a - a0) ** 2);if (t <= tolerance) {imgData.data[i] = 0;imgData.data[i + 1] = 0;imgData.data[i + 2] = 0;imgData.data[i + 3] = 0;}}context.putImageData(imgData, 0, 0);const newBase64 = canvas.toDataURL('image/png');img.src = newBase64;
}
测试示例:
<!DOCTYPE html>
<html><head><title> new document </title><meta name="generator" content="editplus" /><meta name="author" content="" /><meta name="keywords" content="" /><meta name="description" content="" /><style>html,body {background: #c7bbbb;text-align: center;}</style>
</head><body><img id="img"src='https://img-blog.csdnimg.cn/2022020110394629157.png'><script>setTimeout(() => {removeImgBg(document.getElementById('img'));}, 3000);/**清除图片背景颜色 **/function removeImgBg(img) {//背景颜色 白色const rgba = [255, 255, 255, 255];// 容差大小const tolerance = 60;var imgData = null;const [r0, g0, b0, a0] = rgba;var r, g, b, a;const canvas = document.createElement('canvas');const context = canvas.getContext('2d');const w = img.width;const h = img.height;canvas.width = w;canvas.height = h;context.drawImage(img, 0, 0);imgData = context.getImageData(0, 0, w, h);for (let i = 0; i < imgData.data.length; i += 4) {r = imgData.data[i];g = imgData.data[i + 1];b = imgData.data[i + 2];a = imgData.data[i + 3];const t = Math.sqrt((r - r0) ** 2 + (g - g0) ** 2 + (b - b0) ** 2 + (a - a0) ** 2);if (t <= tolerance) {imgData.data[i] = 0;imgData.data[i + 1] = 0;imgData.data[i + 2] = 0;imgData.data[i + 3] = 0;}}context.putImageData(imgData, 0, 0);const newBase64 = canvas.toDataURL('image/png');img.src = newBase64;}</script>
</body></html>
清除前:
清除后: