龙空技术网

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

养心健身体 112

前言:

如今我们对“js怎么改变背景图”大致比较关注,看官们都想要剖析一些“js怎么改变背景图”的相关资讯。那么小编也在网络上汇集了一些对于“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=';>

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

清除前:

清除后:

标签: #js怎么改变背景图