search
HomeWeb Front-endJS TutorialDetailed 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

Detailed explanation of how to use JS to achieve overlay watermark effect

IMG

Detailed explanation of how to use JS to achieve overlay watermark effect

After processing

DIV

Detailed explanation of how to use JS to achieve overlay watermark effect

## IMG

Detailed explanation of how to use JS to achieve overlay watermark effect

Add a "watermark" here (actually it is not a real watermark). When reaching

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(&#39;div&#39;)
        //关联水印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 = &#39;position: absolute;top: 0px;left: 0px;pointer-events:none&#39;
        }
    }
}

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 the

pointer-events:none attribute to the mask label.

You need to add a

parent 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(&#39;body&#39;)[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

Use

canvas 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!

Statement
This article is reproduced at:juejin. If there is any infringement, please contact admin@php.cn delete
JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

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

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

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.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

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: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

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.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

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

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

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.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

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.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool