1.vue组件添加自定义指令
directives: {
watermark: {
bind(el, binding) {
const watermarkText = binding.value || 'WATERMARK';
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
canvas.width = el.offsetWidth;
canvas.height = el.offsetHeight;
ctx.fillStyle = 'rgba(180, 180, 180, 0.3)';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.font = '20px Arial';
ctx.fillText(watermarkText, canvas.width / 2, canvas.height / 2);
const base64 = canvas.toDataURL('image/png');
const watermarkDiv = document.createElement('div');
watermarkDiv.style.position = 'absolute';
watermarkDiv.style.top = '0px';
watermarkDiv.style.left = '0px';
watermarkDiv.style.width = `${el.offsetWidth}px`;
watermarkDiv.style.height = `${el.offsetHeight}px`;
watermarkDiv.style.backgroundImage = `url('${base64}')`;
watermarkDiv.style.pointerEvents = 'none';
el.style.position = 'relative';
el.appendChild(watermarkDiv);
}
}
}
2.组件中使用自定义指令
<template>
<div v-watermark="'Protected Content'">
</div>
</template>