通过添加自定义指定来实现方便的添加文字/图片 水印
// vue3 指令
export function createApp() {
const app = createSSRApp(App);
app.directive('watermark', (el, binding) => {
function addWaterMarker(str1, str2, parentNode, font, textColor) { // str1、str2水印文字,父元素,字体,文字颜色
const img = document.createElement("canvas"); // 创建canvas元素
parentNode.appendChild(img);
img.width = 100;
img.height = 100;
img.style.zIndex = '999'
img.style.display = 'none';
const image = img.getContext("2d"); // 获取canvas画布
image.rotate(-25 * Math.PI / 180); // 逆时针旋转π/9
image.globalAlpha = 1 // 透明度
image.font = font || '18px Microsoft Yauheni ';
image.fillStyle = textColor || 'rgba(200, 200, 200, 1)';
image.textAlign = 'left';
// image.textBaseline = 'Middle';
image.fillText(str1, 15, 80); // 第一行字体
image.fillText(str2, 15, 100); // 第二行字体
parentNode.style.backgroundImage = 'url(' + img.toDataURL('image/png') + ')';
}
addWaterMarker(binding.value.text1, binding.value.text2, el, binding.value.font, binding.value.textColor);
})
return {
app,
};
}
// 调用
<div class="water" v-watermark="{text1:userInfo.account,text2:userInfo.name,textColor:'rgba(0,0,0,.15)'}"></div>
.water {
position: absolute;top:0;left: 0;z-index: 0;width: 100vw;height: 100vh;
}