js 将图片转化成黑白
程序员文章站
2022-07-14 19:20:46
...
效果:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>图片转化成黑白案例</title>
<style>
.conntainer {
display: flex;
}
</style>
</head>
<body>
<div class="conntainer">
<img src="./bg2.jpg" alt="背景图片">
<button onclick="change()">转换</button>
<canvas id="canvas"></canvas>
</div>
<script>
/**
*图片是有许多的像素点组成的,存在在一个特定的数组里面, 每4位为一个像素点,要为黑白的话,取前面3位的平均值就好
*
*/
function change() {
const img = document.querySelector('img');
const cvs = document.getElementById("canvas");
cvs.width = img.width;
cvs.height = img.height;
const ctx = cvs.getContext('2d');
ctx.drawImage(img, 0, 0);
// 获取图片的所有像素点
const imgArrData = ctx.getImageData(0, 0, img.width, img.height);
for (let i = 0; i < imgArrData.data.length; i += 4) {
let r = imgArrData.data[i],
g = imgArrData.data[i + 1],
b = imgArrData.data[i + 2];
const avg = (r + g + b) / 3;
imgArrData.data[i] = imgArrData.data[i + 1] = imgArrData.data[i + 2] = avg;
}
console.log(imgArrData)
ctx.putImageData(imgArrData, 0, 0);
}
</script>
</body>
</html>