


Detailed explanation of how to use JS to achieve overlay watermark effect
Nonsense start: simply implement a small function to cover watermarks. Watermarks are usually added to pictures, and then directly load the processed pictures url. The pictures are not modified here. Instead, directly add a canvas mask to the dom to be added.
1. Effect
Before processing
DIV
IMG
After processing
DIV
DIV, the button click event will not be blocked by the mask. And cannot click
2. JS code
class WaterMark{ //水印文字 waterTexts = [] //需要添加水印的dom集合 needAddWaterTextElementIds = null //保存添加水印的dom saveNeedAddWaterMarkElement = [] //初始化 constructor(waterTexts,needAddWaterTextElementIds){ if(waterTexts && waterTexts.length != 0){ this.waterTexts = waterTexts } else { this.waterTexts = ['水印文字哈哈哈哈','2022-12-08'] } this.needAddWaterTextElementIds = needAddWaterTextElementIds } //开始添加水印 startWaterMark(){ const self = this if(this.needAddWaterTextElementIds){ this.needAddWaterTextElementIds.forEach((id)=>{ let el = document.getElementById(id) self.saveNeedAddWaterMarkElement.push(el) }) } else { this.saveNeedAddWaterMarkElement = Array.from(document.getElementsByTagName('img')) } this.saveNeedAddWaterMarkElement.forEach((el)=>{ self.startWaterMarkToElement(el) }) } //添加水印到到dom对象 startWaterMarkToElement(el){ let nodeName = el.nodeName if(['IMG','img'].indexOf(nodeName) != -1){ //图片,需要加载完成进行操作 this.addWaterMarkToImg(el) } else { //普通,直接添加 this.addWaterMarkToNormalEle(el) } } //给图片添加水印 async addWaterMarkToImg(img){ if(!img.complete){ await new Promise((resolve)=>{ img.onload = resolve }) } this.addWaterMarkToNormalEle(img) } //给普通dom对象添加水印 addWaterMarkToNormalEle(el){ const self = this let canvas = document.createElement('canvas') canvas.width = el.width ? el.width : el.clientWidth canvas.height = el.height ? el.height : el.clientHeight let ctx = canvas.getContext('2d') let maxSize = Math.max(canvas.height, canvas.width) let font = (maxSize / 25) ctx.font = font + 'px "微软雅黑"' ctx.fillStyle = "rgba(195,195,195,1)" ctx.textAlign = "left" ctx.textBaseline = "top" ctx.save() let angle = -Math.PI / 10.0 //进行平移,计算平移的参数 let translateX = (canvas.height) * Math.tan(Math.abs(angle)) let translateY = (canvas.width - translateX) * Math.tan(Math.abs(angle)) ctx.translate(-translateX / 2.0, translateY / 2.0) ctx.rotate(angle) //起始坐标 let x = 0 let y = 0 //一组文字之间间隔 let sepY = (font / 2.0) while(y < canvas.height){ //当前行的y值 let rowCurrentMaxY = 0 while(x < canvas.width){ let totleMaxX = 0 let currentY = 0 //绘制水印 this.waterTexts.forEach((text,index)=>{ currentY += (index * (sepY + font)) let rect = self.drawWater(ctx,text,x,y + currentY) let currentMaxX = (rect.x + rect.width) totleMaxX = (currentMaxX > totleMaxX) ? currentMaxX: totleMaxX rowCurrentMaxY = currentY }) x = totleMaxX + 20 } //重置x,y值 x = 0 y += (rowCurrentMaxY + (sepY + font + (canvas.height / 5))) } ctx.restore() //添加canvas this.addCanvas(canvas,el) } //绘制水印 drawWater(ctx,text,x,y){ //绘制文字 ctx.fillText(text,x,y) //计算尺度 let textRect = ctx.measureText(text) let width = textRect.width let height = textRect.height return {x,y,width,height} } //添加canvas到当前标签的父标签上 addCanvas(canvas,el){ //创建div(canvas需要依赖一个div进行位置设置) let warterMarDiv = document.createElement('div') //关联水印dom对象 el.warterMark = warterMarDiv //添加样式 this.resetCanvasPosition(el) //添加水印 warterMarDiv.appendChild(canvas) //添加到父标签 el.parentElement.insertBefore(warterMarDiv,el) } //重新计算位置 resetCanvasPosition(el){ if(el.warterMark){ //设置父标签的定位 el.parentElement.style.cssText = `position: relative;` //设施水印载体的定位 el.warterMark.style.cssText = 'position: absolute;top: 0px;left: 0px;pointer-events:none' } } }Usage
<div> <!-- 待加水印的IMG --> <img src="/static/imghwm/default1.png" data-src="" alt=" class="lazy" style="max-width:90%" alt=""> </div> let waterMark = new WaterMark() waterMark.startWaterMark();
ctx.save() and ctx .restore() In fact, it is not very useful here, but it is still added. The purpose is to save the context before adding the watermark, and to restore the context before the watermark after finishing drawing. In this way, these italicized words are only in these two It takes effect between lines of code. If you draw other lines below, it will not be affected.
To prevent the mask watermark from blocking underlying buttons or other events, you need to add thepointer-events:none attribute to the mask label.
You need to add aparent tag outside the label to add the watermark. The function of this parent tag is to add constraints to the position of the mask canvas, here I wanted to use MutationObserver to observe changes in body to update the position of maskcanvas. This attempt failed because as long as the complex layout changes, it will be in this callback. trigger in. Therefore, you need to add a parent tag directly outside the tag where the watermark is added, and use this parent tag to automatically constrain the position of the maskcanvas.
MutationObserver The logic is as follows. You can modify the layout or other operations in time in the listening callback (give up temporarily).
var MutationObserver = window.MutationObserver || window.webkitMutationObserver || window.MozMutationObserver; var mutationObserver = new MutationObserver(function (mutations) { //修改水印位置 }) mutationObserver.observe(document.getElementsByTagName('body')[0], { childList: true, // 子节点的变动(新增、删除或者更改) attributes: true, // 属性的变动 characterData: true, // 节点内容或节点文本的变动 subtree: true // 是否将观察器应用于该节点的所有后代节点 })The size of the image can only be determined after the loading is completed. Therefore, for the operation of
IMG, you need to observe its complete event.
3. Summary and thinking
Usecanvas ctx.drawImage(img, 0, 0) to draw, and then canvas .toDataURL('image/png') Loading the generated url to the previous image is also a way. However, sometimes the final composite image will be ## because of the image. #base64 The data is empty, so adding a mask directly is just for display, not to generate a real composite image. A simple pseudo-watermark has been implemented. There is no particularly complicated code. The code is clumsy. Gods should not laugh. 》
The above is the detailed content of Detailed explanation of how to use JS to achieve overlay watermark effect. For more information, please follow other related articles on the PHP Chinese website!

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Chinese version
Chinese version, very easy to use

WebStorm Mac version
Useful JavaScript development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver Mac version
Visual web development tools
