vue 水印组件 水印在最上层,不影响按钮操作

2024-05-24 17:12

本文主要是介绍vue 水印组件 水印在最上层,不影响按钮操作,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

需求

最近项目需要加水印,但是加入的水印必须在最上层,不能影响水印下层的功能正常使用,通过查询找到了一个比较好的水印组件,并按需求优化,记录一下。

效果

在这里插入图片描述

解决方法

因为水印要在最上层,不影响下次功能的正常使用,所有需要使用css样式 pointer-events: none;。

.watermark-container {position: absolute;top: 0;left: 0;width: 100%;height: 100%;pointer-events: none;
}

代码

index.vue

<template><div><Watermark v-if="WatermarkDisplay" :content="WatermarkContent"></Watermark></div>
</template>
<script>
import Watermark from './watermark.vue'
export default {components: {Watermark},data() {return {WatermarkDisplay: true, // 水印状态WatermarkContent: '管理员', // 水印内容}}
}
</script>

watermark.vue

<template><div class="watermark-container"/>
</template><script>
const rate = 350
let lastClick = Date.now() - rate
const BaseSize = 2
const FontGap = 3
const getPixelRatio = () => window.devicePixelRatio || 1
const toLowercaseSeparator = (key) => key.replace(/([A-Z])/g, '-$1').toLowerCase()
const getStyleStr = (style) =>Object.keys(style).map((key) => `${toLowercaseSeparator(key)}: ${style[key]};`).join(' ')function reRendering(mutation, watermarkElement) {let flag = false// 是否删除水印节点if (mutation.removedNodes.length) {flag = Array.from(mutation.removedNodes).some((node) => node === watermarkElement)}// 是否修改过水印dom属性值if (mutation.type === 'attributes' && mutation.target === watermarkElement) {flag = true}return flag
}
export default {name: 'Watermark',data() {return {watermarkRef: null,stopObservation: false,observe: null}},props: {zIndex: { type: Number, default: 9 },rotate: { type: Number, default: 45 },width: { type: [String, Number], default: 120 },height: { type: [String, Number], default: 64 },image: { type: String, default: '' },content: { type: [String, Array], default: '' },font: {type: Object,default: () => ({fontSize: 12,fontFamily: '思源黑体',fontStyle: 'normal',fontWeight: 'normal',color: 'rgba(0, 0, 0, 0.15)'})},clockwise: { type: Boolean, default: false },opacity: { type: Number, default: 1 },rootClassName: null,gap: { type: Array, default: () => [100, 100] },offset: { type: Array, default: () => [100, 50] }},computed: {markStyle() {const props = this.$propsconst [gapX, gapY] = props.gapconst [offsetX, offsetY] = props.offsetconst gapXCenter = gapX / 2const gapYCenter = gapY / 2const offsetTop = offsetY || gapYCenterconst offsetLeft = offsetX || gapXCenterconst markStyle = {zIndex: this.zIndex,opacity: this.opacity,position: 'absolute',left: 0,top: 0,width: '100%',height: '100%',pointerEvents: 'none',backgroundRepeat: 'repeat'}let positionLeft = offsetLeft - gapXCenterlet positionTop = offsetTop - gapYCenterif (positionLeft > 0) {markStyle.left = `${positionLeft}px`markStyle.width = `calc(100% - ${positionLeft}px)`positionLeft = 0}if (positionTop > 0) {markStyle.top = `${positionTop}px`markStyle.height = `calc(100% - ${positionTop}px)`positionTop = 0}markStyle.backgroundPosition = `${positionLeft}px ${positionTop}px`return markStyle}},watch: {$props: {handler() {if (Date.now() - lastClick >= rate) {this.stopObservation = truethis.renderWatermark()// 延迟执行setTimeout(() => {this.stopObservation = falselastClick = Date.now()})}},deep: true}},beforeDestroy() {this.destroyWatermark()this.observe.disconnect()this.observe = null},mounted() {this.renderWatermark()this.$nextTick(() => {this.observe = this.useMutationObserver(this.$el, this.onMutate, { attributes: true, childList: true, subtree: true })})},methods: {onMutate(records) {if (this.stopObservation) returnrecords.forEach((mutation) => {if (!reRendering(mutation, this.watermarkRef)) returnthis.destroyWatermark()this.renderWatermark()})},useMutationObserver(target, callback, options) {const isSupported = typeof MutationObserver !== 'undefined'if (!isSupported) return falseconst observe = new MutationObserver(callback)observe.observe(target, options)return observe},getMarkSize(ctx) {const props = this.$propsconst { fontSize, fontFamily } = props.fontlet defaultWidthlet defaultHeightconst content = props.contentconst image = props.imageconst width = props.widthconst height = props.heightif (!image && ctx.measureText) {ctx.font = `${Number(fontSize)}px ${fontFamily}`const contents = Array.isArray(content) ? content : [content]const widths = contents.map((item) => ctx.measureText(item).width)defaultWidth = Math.ceil(Math.max(...widths))defaultHeight = Number(fontSize.value) * contents.length + (contents.length - 1) * FontGap}return [width ?? defaultWidth, height ?? defaultHeight]},rotateWatermark(ctx, rotateX, rotateY, rotate) {const direction = this.$props.clockwise ? 1 : -1ctx.translate(rotateX, rotateY)ctx.rotate((Math.PI / 180) * Number(rotate) * direction)ctx.translate(-rotateX, -rotateY)},fillTexts(ctx, drawX, drawY, drawWidth, drawHeight) {const props = this.$propsconst { fontSize, fontFamily, fontStyle, fontWeight, color } = props.fontconst ratio = getPixelRatio()const content = props.contentconst mergedFontSize = Number(fontSize) * ratioctx.font = `${fontStyle} normal ${fontWeight} ${mergedFontSize}px/${drawHeight}px ${fontFamily}`ctx.fillStyle = colorctx.textAlign = 'center'ctx.textBaseline = 'top'ctx.translate(drawWidth / 2, 0)const contents = Array.isArray(content) ? content : [content]contents?.forEach((item, index) => {ctx.fillText(item ?? '', drawX, drawY + index * (mergedFontSize + FontGap * ratio))})},appendWatermark(base64Url, markWidth) {if (!this.watermarkRef) returnconst props = this.$propsconst [gapX, gapY] = props.gapthis.stopObservation = trueconst attrs = getStyleStr({ ...this.markStyle, backgroundImage: `url('${base64Url}')`, backgroundSize: `${(gapX + markWidth) * BaseSize}px` })this.watermarkRef.setAttribute('style', attrs)this.$el.append(this.watermarkRef)// 延迟执行setTimeout(() => {this.stopObservation = false})},renderWatermark() {const props = this.$propsconst [gapX, gapY] = props.gapconst canvas = document.createElement('canvas')const ctx = canvas.getContext('2d')const image = props.imageconst rotate = props.rotateif (!ctx) return falseif (!this.watermarkRef) {this.watermarkRef = document.createElement('div')}const ratio = getPixelRatio()const [markWidth, markHeight] = this.getMarkSize(ctx)const canvasWidth = (gapX + markWidth) * ratioconst canvasHeight = (gapY + markHeight) * ratiocanvas.setAttribute('width', `${canvasWidth * BaseSize}px`)canvas.setAttribute('height', `${canvasHeight * BaseSize}px`)const drawX = (gapX * ratio) / 2const drawY = (gapY * ratio) / 2const drawWidth = markWidth * ratioconst drawHeight = markHeight * ratioconst rotateX = (drawWidth + gapX * ratio) / 2const rotateY = (drawHeight + gapY * ratio) / 2/** 备选绘图参数 */const alternateDrawX = drawX + canvasWidthconst alternateDrawY = drawY + canvasHeightconst alternateRotateX = rotateX + canvasWidthconst alternateRotateY = rotateY + canvasHeightctx.save()this.rotateWatermark(ctx, rotateX, rotateY, rotate)if (image) {const img = new Image()img.onload = () => {ctx.drawImage(img, drawX, drawY, drawWidth, drawHeight)/** 旋转后绘制交错图 */ctx.restore()this.rotateWatermark(ctx, alternateRotateX, alternateRotateY, rotate)ctx.drawImage(img, alternateDrawX, alternateDrawY, drawWidth, drawHeight)this.appendWatermark(canvas.toDataURL(), markWidth)}img.crossOrigin = 'anonymous'img.referrerPolicy = 'no-referrer'img.src = image} else {this.fillTexts(ctx, drawX, drawY, drawWidth, drawHeight)/*** 旋转后填充交错的文本* */ctx.restore()this.rotateWatermark(ctx, alternateRotateX, alternateRotateY, rotate)this.fillTexts(ctx, alternateDrawX, alternateDrawY, drawWidth, drawHeight)this.appendWatermark(canvas.toDataURL(), markWidth)}},destroyWatermark() {if (!this.watermarkRef) returnthis.watermarkRef.remove()this.watermarkRef = undefined}}//  End
}
</script><style lang="scss" scoped>
.watermark-container {position: absolute;top: 0;left: 0;width: 100%;height: 100%;pointer-events: none;
}
</style>

参考

借鉴与vue 水印组件
具体参数可以参考
在这里插入图片描述
在这里插入图片描述

这篇关于vue 水印组件 水印在最上层,不影响按钮操作的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/999019

相关文章

Python实现对阿里云OSS对象存储的操作详解

《Python实现对阿里云OSS对象存储的操作详解》这篇文章主要为大家详细介绍了Python实现对阿里云OSS对象存储的操作相关知识,包括连接,上传,下载,列举等功能,感兴趣的小伙伴可以了解下... 目录一、直接使用代码二、详细使用1. 环境准备2. 初始化配置3. bucket配置创建4. 文件上传到os

mysql表操作与查询功能详解

《mysql表操作与查询功能详解》本文系统讲解MySQL表操作与查询,涵盖创建、修改、复制表语法,基本查询结构及WHERE、GROUPBY等子句,本文结合实例代码给大家介绍的非常详细,感兴趣的朋友跟随... 目录01.表的操作1.1表操作概览1.2创建表1.3修改表1.4复制表02.基本查询操作2.1 SE

c++中的set容器介绍及操作大全

《c++中的set容器介绍及操作大全》:本文主要介绍c++中的set容器介绍及操作大全,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录​​一、核心特性​​️ ​​二、基本操作​​​​1. 初始化与赋值​​​​2. 增删查操作​​​​3. 遍历方

MySQL追踪数据库表更新操作来源的全面指南

《MySQL追踪数据库表更新操作来源的全面指南》本文将以一个具体问题为例,如何监测哪个IP来源对数据库表statistics_test进行了UPDATE操作,文内探讨了多种方法,并提供了详细的代码... 目录引言1. 为什么需要监控数据库更新操作2. 方法1:启用数据库审计日志(1)mysql/mariad

springboot如何通过http动态操作xxl-job任务

《springboot如何通过http动态操作xxl-job任务》:本文主要介绍springboot如何通过http动态操作xxl-job任务的问题,具有很好的参考价值,希望对大家有所帮助,如有错... 目录springboot通过http动态操作xxl-job任务一、maven依赖二、配置文件三、xxl-

前端如何通过nginx访问本地端口

《前端如何通过nginx访问本地端口》:本文主要介绍前端如何通过nginx访问本地端口的问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、nginx安装1、下载(1)下载地址(2)系统选择(3)版本选择2、安装部署(1)解压(2)配置文件修改(3)启动(4)

HTML中meta标签的常见使用案例(示例详解)

《HTML中meta标签的常见使用案例(示例详解)》HTMLmeta标签用于提供文档元数据,涵盖字符编码、SEO优化、社交媒体集成、移动设备适配、浏览器控制及安全隐私设置,优化页面显示与搜索引擎索引... 目录html中meta标签的常见使用案例一、基础功能二、搜索引擎优化(seo)三、社交媒体集成四、移动

HTML input 标签示例详解

《HTMLinput标签示例详解》input标签主要用于接收用户的输入,随type属性值的不同,变换其具体功能,本文通过实例图文并茂的形式给大家介绍HTMLinput标签,感兴趣的朋友一... 目录通用属性输入框单行文本输入框 text密码输入框 password数字输入框 number电子邮件输入编程框

HTML img标签和超链接标签详细介绍

《HTMLimg标签和超链接标签详细介绍》:本文主要介绍了HTML中img标签的使用,包括src属性(指定图片路径)、相对/绝对路径区别、alt替代文本、title提示、宽高控制及边框设置等,详细内容请阅读本文,希望能对你有所帮助... 目录img 标签src 属性alt 属性title 属性width/h

CSS3打造的现代交互式登录界面详细实现过程

《CSS3打造的现代交互式登录界面详细实现过程》本文介绍CSS3和jQuery在登录界面设计中的应用,涵盖动画、选择器、自定义字体及盒模型技术,提升界面美观与交互性,同时优化性能和可访问性,感兴趣的朋... 目录1. css3用户登录界面设计概述1.1 用户界面设计的重要性1.2 CSS3的新特性与优势1.