龙空技术网

JavaScript 清除图片背景颜色 使之透明

养心健身体 146

前言:

而今姐妹们对“html改变背景”可能比较关心,同学们都需要分析一些“html改变背景”的相关知识。那么小编同时在网摘上收集了一些关于“html改变背景””的相关文章,希望姐妹们能喜欢,你们一起来学习一下吧!

主要

/**清除图片背景颜色 **/

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=';>

<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>

清除前:

清除后:

标签: #html改变背景