feat: 🚀 水印指令

This commit is contained in:
bunny 2024-05-10 13:12:01 +08:00
parent 277e4e8474
commit 8f22479002
4 changed files with 47 additions and 6 deletions

View File

@ -1,7 +1,8 @@
import { App, Directive } from 'vue'; import { App, Directive } from 'vue';
import copy from './modules/copy'; import copy from './modules/copy';
import waterMarker from './modules/waterMarker';
const directivesList: { [key: string]: Directive } = { copy }; const directivesList: { [key: string]: Directive } = { copy, waterMarker };
/** /**
* *

View File

@ -7,7 +7,9 @@ interface ElType extends HTMLElement {
} }
/** /**
* * * v-copy
*
* string类型/Ref<string>/Reactive<string>
*/ */
const copy: Directive = { const copy: Directive = {
mounted(el: ElType, binding: DirectiveBinding) { mounted(el: ElType, binding: DirectiveBinding) {
@ -26,7 +28,7 @@ const copy: Directive = {
}; };
/** /**
* * *
* @param this * @param this
*/ */
function handelClick(this: any) { function handelClick(this: any) {

View File

@ -0,0 +1,36 @@
import type { Directive, DirectiveBinding } from 'vue';
const addWaterMarker: Directive = (str: string, parentNode: any, font: any, textColor: string) => {
// 创建一个canvas元素
let can: HTMLCanvasElement = document.createElement('canvas');
// 将canvas元素添加到父元素中
parentNode.appendChild(can);
// 设置canvas元素的宽高
can.width = 205;
can.height = 140;
// 隐藏canvas元素
can.style.display = 'none';
// 获取canvas元素的2d上下文
let cans = can.getContext('2d') as CanvasRenderingContext2D;
// 旋转canvas元素
cans.rotate((-20 * Math.PI) / 180);
// 设置canvas元素的字体和文字颜色
cans.font = font || '16px Microsoft JhengHei';
cans.fillStyle = textColor || 'rgba(180, 180, 180, 0.3)';
// 设置canvas元素的文本对齐方式和基线
cans.textAlign = 'left';
cans.textBaseline = 'Middle' as CanvasTextBaseline;
// 在canvas元素上绘制文本
cans.fillText(str, can.width / 10, can.height / 2);
// 将父元素的背景图片设置为canvas元素的dataURL
parentNode.style.backgroundImage = `url("${can.toDataURL('image/png')}")`;
};
const waterMarker: Directive = {
mounted(el: DirectiveBinding, binding: DirectiveBinding) {
// 调用addWaterMarker函数给元素添加水印
addWaterMarker(binding.value.text, el, binding.value.font, binding.value.textColor);
},
};
export default waterMarker;

View File

@ -1,7 +1,9 @@
<template> <template>
<h1>bunny/default页面</h1> <div v-waterMarker="{ text: 'Bunny Admin', textColor: 'rgba(180, 180, 180, 0.6)' }">
<My /> <h1>bunny/default页面</h1>
<RouterView /> <My />
<RouterView />
</div>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">