基于react-hooks封装图片水印和马赛克的方法
const picWaterMark = ({
url = '',
textAlign = 'center',
textBaseline = 'middle',
content = '水印水印水印',
callback = null,
}) => {
const img = new Image();
img.src = url;
img.crossOrigin = 'anonymous';
img.onload = function() {
const canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, img.width,img.height);
const size = 5;
const oldImg = ctx.getImageData(0,0,img.width,img.height)
const newImg = ctx.createImageData(img.width,img.height)
for(var i = 0; i < oldImg.width; i++) {
for(var j = 0; j < oldImg.height; j++) {
var color = getPxInfo(oldImg, Math.floor(i * size + Math.random() * size), Math.floor(j * size + Math.random() * size))
for(var a = 0; a < size; a++) {
for(var b = 0; b < size; b++) {
setPxInfo(newImg, i * size + a, j * size + b, color);
}
}
}
}
ctx.putImageData(newImg, 0, 0)
function getPxInfo(imgDate, x, y) {
var colorArr = [];
var width = imgDate.width;
colorArr[0] = imgDate.data[(width * y + x) * 4 + 0]
colorArr[1] = imgDate.data[(width * y + x) * 4 + 1]
colorArr[2] = imgDate.data[(width * y + x) * 4 + 2]
colorArr[3] = imgDate.data[(width * y + x) * 4 + 3]
return colorArr;
}
function setPxInfo(imgDate, x, y, colors) {
var width = imgDate.width;
imgDate.data[(width * y + x) * 4 + 0] = colors[0];
imgDate.data[(width * y + x) * 4 + 1] = colors[1];
imgDate.data[(width * y + x) * 4 + 2] = colors[2];
imgDate.data[(width * y + x) * 4 + 3] = colors[3];
}
ctx.textAlign = textAlign;
ctx.textBaseline = textBaseline;
ctx.fillStyle = 'red';
ctx.fillText(content, img.width-45,img.height-15);
const base64Url = canvas.toDataURL();
回调函数将base64Url传入
callback && callback(base64Url);
}
}
实际调用
const [url, setUrl] = useState('')
picWaterMark({
url: ’https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png‘,
content: '这里是水印内容',
callback: (base64Url) => {
console.log(base64Url)
setUrl(base64Url)
}
})
<img src={url} alt=''/>
效果图展示