w-vue-middle
Version:
统一公共服务组件
73 lines (67 loc) • 2.95 kB
JavaScript
/*
* @Author: Jason Liu
* @Date: 2022-03-08 15:51:32
* @Desc: 水印
*/
import Vue from 'vue'
Vue.directive('watermark', (el, binding) => {
el.style.position = "fixed";
el.style.top = "0";
el.style.left = "0";
el.style.right = "0";
el.style.zIndex = 1;
el.style.bottom = "0";
el.style.pointerEvents = "none";
function addWaterMarker(str, parentNode, font, textColor) { // 水印文字,父元素,字体,文字颜色
const waterMarkText = localStorage.getItem("waterMarkText")
var can = document.createElement('canvas');
parentNode.appendChild(can);
can.width = binding.value.width || 300;
can.height = binding.value.height || 200;
can.style.display = 'none';
var cans = can.getContext('2d');
cans.rotate((binding.value.angle || -20) * Math.PI / 260);
cans.font = `${font || 14}px Microsoft JhengHei`;
// cans.fillStyle = textColor || "rgba(0, 0, 0, 0.1)";
cans.fillStyle = textColor || "rgb(0, 0, 0)";
cans.textAlign = 'center';
cans.textBaseline = 'Middle';
if (binding.value.type == 'img') {
let imgScale = 0.3;
let img = new Image();
//指定图片的URL
img.src = str;
//浏览器加载图片完毕后再绘制图片
img.onload = function() {
cans.drawImage(img, //规定要使用的图像、画布或视频。
0, 0, //开始剪切的 x 坐标位置。
img.width, img.height, //被剪切图像的高度。
0, 50, //在画布上放置图像的 x 、y坐标位置。
can.width * imgScale, can.height * imgScale //要使用的图像的宽度、高度
)
cans.clearRect(0, 0, can.width * imgScale, can.height * imgScale)
parentNode.style.opacity = 0.3
parentNode.style.background = 'url(' + can.toDataURL('image/png', 0.3) + ')'
};
} else {
// parentNode.style.opacity = 1;
parentNode.style.opacity = binding.value.opacity || 0.1;
let text = str || waterMarkText;
if (str && str.indexOf("\n") > -1) {
let subs = str.split("\n");
let end = 60;
let i = 1;
subs.forEach((t) => {
if (t) {
cans.fillText(t, can.width / subs.length, end + i * 15);
i++;
}
});
} else {
cans.fillText(text, can.width / 3, can.height / 2);
}
parentNode.style.backgroundImage = "url(" + can.toDataURL("image/png") + ")";
}
}
addWaterMarker(binding.value.text, el, binding.value.font, binding.value.textColor);
})