前端利用canvas给图片添加水印
web前端开发
共 2897字,需浏览 6分钟
·
2020-12-12 10:01
来源 | https://wintc.top/article/27
一、本地读取图像文件渲染到img标签
function blobToImg (blob) {
return new Promise((resolve, reject) => {
let reader = new FileReader()
reader.addEventListener('load', () => {
let img = new Image()
img.src = reader.result
img.addEventListener('load', () => resolve(img))
})
reader.readAsDataURL(blob)
})
}
二、将img标签内容绘制到canvas画布
function imgToCanvas (img) {
let canvas = document.createElement('canvas')
canvas.width = img.width
canvas.height = img.height
let ctx = canvas.getContext('2d')
ctx.drawImage(img, 0, 0)
return canvas
}
三、canvas画布上绘制水印并转换为Blob对象
function watermark (canvas, text) {
return new Promise((resolve, reject) => {
let ctx = canvas.getContext('2d')
// 设置填充字号和字体,样式
ctx.font = "24px 宋体"
ctx.fillStyle = "#FFC82C"
// 设置右对齐
ctx.textAlign = 'right'
// 在指定位置绘制文字,这里指定距离右下角20坐标的地方
ctx.fillText(text, canvas.width - 20, canvas.height - 20)
canvas.toBlob(blob => resolve(blob))
})
}
四、图片添加水印完整接口
function imgWatermark (dom, text) {
let input = document.createElement('input')
input.setAttribute('type', 'file')
input.setAttribute('accept', 'image/*')
input.onchange = async () => {
let img = await blobToImg(input.files[0])
let canvas = imgToCanvas(img)
let blob = await watermark(canvas, text)
// 此处将Blob读取到img标签,并在dom内渲染出来;如果是上传文件,可以将blob添加到FormData中
let newImage = await blobToImg(blob)
dom.appendChild(newImage)
}
input.click()
}
给页面加一个id为container的div元素,然后如下调用:
let dom = document.querySelector('#container')
imgWatermark(dom, '水印文字')
![](https://filescdn.proginn.com/bedf1da8813958b54ce3ddd29c109965/80fd57b73d9c36b99404066d4f6ad6df.webp)
![](https://filescdn.proginn.com/bbe94074dc3f1b76150af0aad02d02a8/e9c6d9b49cacedb7266ff3e418f795a2.webp)
五、总结
![](https://filescdn.proginn.com/89661dcfc9a2b3b0b6783c48e6ba675c/c9bd4606cddd708d5381812a7cd1b119.webp)
评论