使用canvas给图片添加滤镜
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<canvas id="canvas" width="600" height="600"></canvas>
<div>
<button id="btn1">灰阶</button>
</div>
</body>
<script>
const canvas = document.querySelector('#canvas');
const ctx = canvas.getContext('2d');
const image = new Image();
image.onload = function() {
const width = image.width;
const height = image.height;
canvas.width = width;
canvas.height = height;
ctx.drawImage(image, 0, 0, width, height);
}
image.src = 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Finews.gtimg.com%2Fnewsapp_match%2F0%2F8623835034%2F0.jpg&refer=http%3A%2F%2Finews.gtimg.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1665063480&t=db0d36975e3c9893beec1490838d419f'
// image.src = 'https://img0.baidu.com/it/u=461167198,1004148544&fm=253&fmt=auto&app=138&f=JPEG?w=640&h=400';
image.setAttribute('crossOrigin', '*');
function grayImage(data) {
let r, g, b, a;
let average;
for (let i = 0; i < data.length; i += 4) {
r = data[i];
g = data[i + 1];
b = data[i + 2];
r = data[i + 3];
average = Math.floor((r + g + b) / 3);
data[i] = average;
data[i + 1] = average;
data[i + 2] = average;
}
return data;
}
btn1.onclick = function() {
const imageData = ctx.getImageData(0, 0, image.width, image.height);
const data = imageData.data;
image.data = grayImage(data);
ctx.putImageData(imageData, 0, 0);
}
</script>
</html>
效果: https://code.juejin.cn/pen/7129481786740080681
(进去后点击下运行)