vue-watermark-sdk
Version:
99 lines (75 loc) • 3.32 kB
JavaScript
export default {
install(Vue, options) {
const defaultOptions = {
text: '',
fontSize: '20px',
color: 'rgba(0, 0, 0, 0.1)',
rotation: -30,
zIndex: 9999,
gap: 50, // 水印之间的间隔
};
const createWatermark = (settings, el) => {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
canvas.width = 2000;
canvas.height = 2000;
// 计算完整的文本宽高
const textWidth = ctx.measureText(settings.text).width;
// 避免旋转后的空白
const radians = Math.abs(settings.rotation) * (Math.PI / 180);
const translateWidth = el.clientHeight * Math.tan(radians)
ctx.font = `${settings.fontSize} sans-serif`;
ctx.fillStyle = settings.color;
ctx.textAlign = 'left';
ctx.textBaseline = 'middle';
ctx.rotate((Math.PI / 180) * settings.rotation);
// 设置水印文本的间隔
const textInterval = 2 * textWidth + settings.gap;
// 循环绘制水印文本
for (let x = -translateWidth; x < canvas.width; x += textInterval) {
for (let y = -2 * textWidth; y < canvas.height; y += 50) {
ctx.fillText(settings.text, x, y);
}
}
el.style.position = 'relative';
// 创建水印 div
const watermarkDiv = document.createElement('div');
watermarkDiv.style.pointerEvents = 'none';
watermarkDiv.style.className = 'watermark-canvas'; // 添加类名以便于选择
watermarkDiv.style.position = 'absolute';
watermarkDiv.style.top = '0';
watermarkDiv.style.left = '0';
watermarkDiv.style.width = '100%';
watermarkDiv.style.height = '100%';
watermarkDiv.style.zIndex = settings.zIndex;
watermarkDiv.style.background = `url(${canvas.toDataURL('image/png')})`;
el.appendChild(watermarkDiv);
el._watermarkDiv = watermarkDiv;
}
const settings = { ...defaultOptions, ...options };
Vue.directive('watermark', {
bind(el, binding, vNode) {
// console.log('bind', binding)
// 使用 vnode.context 访问 Vue 实例
const vm = vNode.context;
vm.$nextTick(() => {
createWatermark(settings, el);
});
},
unbind(el) {
// console.log('unbind', el)
// while (el.firstChild) {
// el.removeChild(el.firstChild);
// }
// 清除水印
el.removeChild(el._watermarkDiv);
},
update(el, binding) {
// console.log('update', binding)
// console.log('settings',settings)
el.removeChild(el._watermarkDiv);
createWatermark({ ...settings, text: `${binding.value.text}` }, el);
}
});
}
};