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

相关文章

在C#中分离饼图的某个区域的操作指南

《在C#中分离饼图的某个区域的操作指南》在处理Excel饼图时,我们可能需要将饼图的各个部分分离出来,以使它们更加醒目,Spire.XLS提供了Series.DataFormat.Percent属性,... 目录引言如何设置饼图各分片之间分离宽度的代码示例:从整个饼图中分离单个分片的代码示例:引言在处理

Python列表的创建与删除的操作指南

《Python列表的创建与删除的操作指南》列表(list)是Python中最常用、最灵活的内置数据结构之一,它支持动态扩容、混合类型、嵌套结构,几乎无处不在,但你真的会创建和删除列表吗,本文给大家介绍... 目录一、前言二、列表的创建方式1. 字面量语法(最常用)2. 使用list()构造器3. 列表推导式

HTML5的input标签的`type`属性值详解和代码示例

《HTML5的input标签的`type`属性值详解和代码示例》HTML5的`input`标签提供了多种`type`属性值,用于创建不同类型的输入控件,满足用户输入的多样化需求,从文本输入、密码输入、... 目录一、引言二、文本类输入类型2.1 text2.2 password2.3 textarea(严格

Go异常处理、泛型和文件操作实例代码

《Go异常处理、泛型和文件操作实例代码》Go语言的异常处理机制与传统的面向对象语言(如Java、C#)所使用的try-catch结构有所不同,它采用了自己独特的设计理念和方法,:本文主要介绍Go异... 目录一:异常处理常见的异常处理向上抛中断程序恢复程序二:泛型泛型函数泛型结构体泛型切片泛型 map三:文

SpringBoot返回文件让前端下载的几种方式

《SpringBoot返回文件让前端下载的几种方式》文章介绍了开发中文件下载的两种常见解决方案,并详细描述了通过后端进行下载的原理和步骤,包括一次性读取到内存和分块写入响应输出流两种方法,此外,还提供... 目录01 背景02 一次性读取到内存,通过响应输出流输出到前端02 将文件流通过循环写入到响应输出流

SpringBoot+Vue3整合SSE实现实时消息推送功能

《SpringBoot+Vue3整合SSE实现实时消息推送功能》在日常开发中,我们经常需要实现实时消息推送的功能,这篇文章将基于SpringBoot和Vue3来简单实现一个入门级的例子,下面小编就和大... 目录前言先大概介绍下SSE后端实现(SpringBoot)前端实现(vue3)1. 数据类型定义2.

JavaWeb 中的 Filter组件详解

《JavaWeb中的Filter组件详解》本文详细介绍了JavaWeb中的Filter组件,包括其基本概念、工作原理、核心接口和类、配置方式以及常见应用示例,Filter可以实现请求预处理、响应后... 目录JavaWeb 中的 Filter 详解1. Filter 基本概念1.1 什么是 Filter1.

MySQL基本表查询操作汇总之单表查询+多表操作大全

《MySQL基本表查询操作汇总之单表查询+多表操作大全》本文全面介绍了MySQL单表查询与多表操作的关键技术,包括基本语法、高级查询、表别名使用、多表连接及子查询等,并提供了丰富的实例,感兴趣的朋友跟... 目录一、单表查询整合(一)通用模版展示(二)举例说明(三)注意事项(四)Mapper简单举例简单查询

Nginx概念、架构、配置与虚拟主机实战操作指南

《Nginx概念、架构、配置与虚拟主机实战操作指南》Nginx是一个高性能的HTTP服务器、反向代理服务器、负载均衡器和IMAP/POP3/SMTP代理服务器,它支持高并发连接,资源占用低,功能全面且... 目录Nginx 深度解析:概念、架构、配置与虚拟主机实战一、Nginx 的概念二、Nginx 的特点

2025最新版Android Studio安装及组件配置教程(SDK、JDK、Gradle)

《2025最新版AndroidStudio安装及组件配置教程(SDK、JDK、Gradle)》:本文主要介绍2025最新版AndroidStudio安装及组件配置(SDK、JDK、Gradle... 目录原生 android 简介Android Studio必备组件一、Android Studio安装二、A