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

相关文章

Java使用Stream流的Lambda语法进行List转Map的操作方式

《Java使用Stream流的Lambda语法进行List转Map的操作方式》:本文主要介绍Java使用Stream流的Lambda语法进行List转Map的操作方式,具有很好的参考价值,希望对大... 目录背景Stream流的Lambda语法应用实例1、定义要操作的UserDto2、ListChina编程转成M

Git可视化管理工具(SourceTree)使用操作大全经典

《Git可视化管理工具(SourceTree)使用操作大全经典》本文详细介绍了SourceTree作为Git可视化管理工具的常用操作,包括连接远程仓库、添加SSH密钥、克隆仓库、设置默认项目目录、代码... 目录前言:连接Gitee or github,获取代码:在SourceTree中添加SSH密钥:Cl

使用Java将各种数据写入Excel表格的操作示例

《使用Java将各种数据写入Excel表格的操作示例》在数据处理与管理领域,Excel凭借其强大的功能和广泛的应用,成为了数据存储与展示的重要工具,在Java开发过程中,常常需要将不同类型的数据,本文... 目录前言安装免费Java库1. 写入文本、或数值到 Excel单元格2. 写入数组到 Excel表格

Python中pywin32 常用窗口操作的实现

《Python中pywin32常用窗口操作的实现》本文主要介绍了Python中pywin32常用窗口操作的实现,pywin32主要的作用是供Python开发者快速调用WindowsAPI的一个... 目录获取窗口句柄获取最前端窗口句柄获取指定坐标处的窗口根据窗口的完整标题匹配获取句柄根据窗口的类别匹配获取句

Python位移操作和位运算的实现示例

《Python位移操作和位运算的实现示例》本文主要介绍了Python位移操作和位运算的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一... 目录1. 位移操作1.1 左移操作 (<<)1.2 右移操作 (>>)注意事项:2. 位运算2.1

Python ZIP文件操作技巧详解

《PythonZIP文件操作技巧详解》在数据处理和系统开发中,ZIP文件操作是开发者必须掌握的核心技能,Python标准库提供的zipfile模块以简洁的API和跨平台特性,成为处理ZIP文件的首选... 目录一、ZIP文件操作基础三板斧1.1 创建压缩包1.2 解压操作1.3 文件遍历与信息获取二、进阶技

Java中字符串转时间与时间转字符串的操作详解

《Java中字符串转时间与时间转字符串的操作详解》Java的java.time包提供了强大的日期和时间处理功能,通过DateTimeFormatter可以轻松地在日期时间对象和字符串之间进行转换,下面... 目录一、字符串转时间(一)使用预定义格式(二)自定义格式二、时间转字符串(一)使用预定义格式(二)自

HTML5中的Microdata与历史记录管理详解

《HTML5中的Microdata与历史记录管理详解》Microdata作为HTML5新增的一个特性,它允许开发者在HTML文档中添加更多的语义信息,以便于搜索引擎和浏览器更好地理解页面内容,本文将探... 目录html5中的Mijscrodata与历史记录管理背景简介html5中的Microdata使用M

html5的响应式布局的方法示例详解

《html5的响应式布局的方法示例详解》:本文主要介绍了HTML5中使用媒体查询和Flexbox进行响应式布局的方法,简要介绍了CSSGrid布局的基础知识和如何实现自动换行的网格布局,详细内容请阅读本文,希望能对你有所帮助... 一 使用媒体查询响应式布局        使用的参数@media这是常用的

HTML5表格语法格式详解

《HTML5表格语法格式详解》在HTML语法中,表格主要通过table、tr和td3个标签构成,本文通过实例代码讲解HTML5表格语法格式,感兴趣的朋友一起看看吧... 目录一、表格1.表格语法格式2.表格属性 3.例子二、不规则表格1.跨行2.跨列3.例子一、表格在html语法中,表格主要通过< tab