背景
有一天突然想着给图片加水印的事情,就想着来实现一下.
环境
使用vue-cli建了一个简单项目
思路
使用canvas技术, 先将图片导入至canvas,在canvas中加水印图片,达到盖章的效果。
实现
导入图片
// 导入图片
importImg() {
const input = document.createElement("input");
const context = this.$refs.canvas.getContext("2d"); // this.$refs.canvas是canvas的dom对象
input.type = "file";
input.click();
input.onchange = () => {
const file = input.files[0];
if (file.type.indexOf("image") == 0) {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => {
const img = new Image();
img.src = reader.result;
img.onload = () => {
let imgW = img.width;
let imgH = img.height;
const width = this.$refs.main.offsetWidth;
const height = this.$refs.main.offsetHeight;
if (imgH > imgW) {
this.$refs.canvas.width = (imgW * height) / imgH;
this.$refs.canvas.height = height;
context.drawImage(img, 0, 0, (imgW * height) / imgH, height);
console.log((imgW * height) / imgH, height);
} else {
this.$refs.canvas.width = width;
this.$refs.canvas.height = (imgH * width) / imgW;
context.drawImage(img, 0, 0, width, (imgH * width) / imgW);
console.log(width, (imgH * width) / imgW);
}
};
};
}
};
FileReade解释 Image对象
盖章
import icon from "./assets/logo.png";
// 印章
addMark(e) { // addMark为canvas点击事件
const img = new Image();
img.src = icon; // icon是要盖的图片
img.onload = () => {
const context = this.$refs.canvas.getContext("2d");
context.drawImage(
img,
e.offsetX - this.markWidth / 2, // markWidth是印章的宽度
e.offsetY - this.markHeight / 2, // markHeight是印章的高度
this.markWidth,
this.markHeight
);
};
},
转换
// 生成图片
downImg() {
this.$refs.canvas.toBlob((blob) => {
let url = window.URL.createObjectURL(blob);
let link = document.createElement("a");
link.href = url;
link.download = "加水印";
link.target = "_blank";
link.click();
});
},
HTMLCanvasElement.toBlob()
成果
常见问题FAQ
- 免费下载或者VIP会员专享资源能否直接商用?
- 本站所有资源版权均属于原作者所有,这里所提供资源均只能用于参考学习用,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担。更多说明请参考 VIP介绍。
- 提示下载完但解压或打开不了?
- 找不到素材资源介绍文章里的示例图片?
- 模板不会安装或需要功能定制以及二次开发?
发表评论
还没有评论,快来抢沙发吧!