veu 上传图片加水印
功能实现: canvas + vant-ui
需要全局引入 vant 的 Icon Uploader Button 组件
效果图:
代码:
<template>
<div class="TaskSubmit">
<div class="showImg" v-show="!isShow">
<img id="myCanvas" :src="fileList" />
<van-icon @click="ondel" class="icon" name="cross"></van-icon>
</div>
<div class="upload" v-show="isShow">
<van-uploader :after-read="onRead" :max-count="1" accept="image/*"></van-uploader>
</div>
<van-button class="button" @click="afterRead" >提交</van-button>
</div>
</template>
<script>
export default {
data(){
return{
fileList: '',
isShow:true,
}
},
created(){
},
methods:{
onRead(file){
this.shuiyin({
url: file.content,
content: "我是水印",
cb: base64Url => {
console.log(base64Url) //转换完成的base64格式图片
this.fileList = base64Url
this.isShow = !this.isShow
}
});
},
shuiyin({
url = "",
textAlign = "left",
textBaseline = "top",
font = "18px Microsoft Yahei",
fillStyle = "rgba(255, 255, 255, .5)",
content = "",
cb = null
} = {}) {
const img = new Image();
img.src = url;
img.crossOrigin = "anonymous";
img.onload = function () {
const canvas = document.createElement("canvas");
let _ix = img.width;
let _iy = img.height;
canvas.width = _ix;
canvas.height = _iy;
const ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
ctx.textAlign = textAlign;
ctx.textBaseline = textBaseline;
ctx.font = font;
ctx.fillStyle = fillStyle;
ctx.translate(0, 0);
ctx.rotate((Math.PI / 180) * 15);//旋转
//水印密度
for (let i = 0; i < _iy / 120; i++) {
for (let j = 0; j < _ix / 50; j++) {
ctx.fillText(content, i * 120, j * 50, _ix);
}
}
const base64Url = canvas.toDataURL();
cb && cb(base64Url);
};
},
ondel(){
this.fileList={}
this.isShow = !this.isShow
},
afterRead() {},
}
}
</script>
<style lang="less" >
.TaskSubmit{
.upload{
padding: 0 10px;
margin-top: 20px;
}
.showImg{
position: relative;
padding: 10px;
img{
width: 100%;
}
.icon{
position: absolute;
right: 10px;
top: 10px;
color: red;
}
}
.van-uploader__upload{
width: 270px;
height: 180px;
margin: 0px 0 0 40px;
}
.button{
width: 270px;
height: 40px;
border: 0;
border-radius: 5px;
font-size: 13px;
color: #fff;
background-color: #fd3838;
margin: 40px 0 50px 50px;
cursor:pointer;
}
}
</style>