vue3关于为元素动态添加文字水印的自定义指令(防篡改)

参数

  • value
    • visible:水印是否可见
    • width:单个水印宽度
    • height:单个水印高度
    • angle:水印旋转角度
    • color:水印的文字颜色
    • content:水印内容

vWatermark.js 文件

import { watch } from 'vue'

export const vWatermark = (watermark, binding) => {
    const canvas = document.createElement("canvas");
    const {
        arg,
        value: {
            visible = true,
            width = 240,
            height = 120,
            angle = -20 * Math.PI / 180,
            color = "rgba(0, 0, 0, .1)",
            content = "水印"
        },
        modifiers
    } = binding

    canvas.width = width;
    canvas.height = height;

    const ctx = canvas.getContext("2d");

    ctx.font = '18px serif'
    ctx.translate(width / 2, height / 2)
    ctx.rotate(angle)
    ctx.textAlign = "center"
    ctx.textBaseline = "middle"
    ctx.fillStyle = color
    ctx.fillText(content, 0, 0)
    const bgImg = canvas.toDataURL("image/png")

    // 使用MutationObserver监听水印元素,防篡改
    const obs = new MutationObserver(records => {
        for(const record of records) {
            // 如果是修改水印元素Style,判断设置水印
            if(record.target === watermark) {
                watermark.style.backgroundImage = watermark.style._visible ? `url(${bgImg})` : "none"
            }
            for(const item of record.removedNodes) {
                // 如果是删除水印元素,判断设置水印
                if(item === watermark) {
                    watermark.style.backgroundImage = watermark.style._visible ? `url(${bgImg})` : "none"
                }
            }
        }
    })

    obs.observe(document.body,{
        childList: true,
        subtree: true,
        attributes: true
    })

    // 监听响应式变量,控制设置元素的水印背景
    watch(
        () => visible,
        () => {
            if (visible) {
                watermark.style._visible = true
                watermark.style.backgroundImage = 'url(' + bgImg + ')'
            } else {
                watermark.style._visible = false
                watermark.style.backgroundImage = "none"
                // 关闭MutationObserver监听
                // obs.disconnect();
            }
        },
        {immediate: true}
    )
}

示例

<script setup>
import {ref} from "vue
import { vWatermark } from "./vWatermark .js"

const visible = ref(false)
</script>

<template>
	<button @click="visible = !visible">按钮</button>
    <div style="background-color: #fff;width: 500px;height: 500px;">
        <div v-watermark="{visible,content: '这是一个水印'}" style="width: 100%;height: 100%;border: 1px solid #666">
        </div>
    </div>
</template>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值