Home Web Front-end JS Tutorial Detailed explanation of how to use JS to achieve overlay watermark effect

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

Mar 03, 2023 pm 03:57 PM
javascript front end

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;
        }
    }
}
Copy after login

Usage

<div>
    <!-- 待加水印的IMG -->
    <img src="/static/imghw/default1.png"  data-src="" alt="  class="lazy"    style="max-width:90%"  alt="">
</div>

let waterMark = new WaterMark()
waterMark.startWaterMark();
Copy after login

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 // 是否将观察器应用于该节点的所有后代节点
})
Copy after login

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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1669
14
PHP Tutorial
1273
29
C# Tutorial
1256
24
WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

PHP and Vue: a perfect pairing of front-end development tools PHP and Vue: a perfect pairing of front-end development tools Mar 16, 2024 pm 12:09 PM

PHP and Vue: a perfect pairing of front-end development tools. In today's era of rapid development of the Internet, front-end development has become increasingly important. As users have higher and higher requirements for the experience of websites and applications, front-end developers need to use more efficient and flexible tools to create responsive and interactive interfaces. As two important technologies in the field of front-end development, PHP and Vue.js can be regarded as perfect tools when paired together. This article will explore the combination of PHP and Vue, as well as detailed code examples to help readers better understand and apply these two

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Is Django front-end or back-end? check it out! Is Django front-end or back-end? check it out! Jan 19, 2024 am 08:37 AM

Django is a web application framework written in Python that emphasizes rapid development and clean methods. Although Django is a web framework, to answer the question whether Django is a front-end or a back-end, you need to have a deep understanding of the concepts of front-end and back-end. The front end refers to the interface that users directly interact with, and the back end refers to server-side programs. They interact with data through the HTTP protocol. When the front-end and back-end are separated, the front-end and back-end programs can be developed independently to implement business logic and interactive effects respectively, and data exchange.

Exploring Go language front-end technology: a new vision for front-end development Exploring Go language front-end technology: a new vision for front-end development Mar 28, 2024 pm 01:06 PM

As a fast and efficient programming language, Go language is widely popular in the field of back-end development. However, few people associate Go language with front-end development. In fact, using Go language for front-end development can not only improve efficiency, but also bring new horizons to developers. This article will explore the possibility of using the Go language for front-end development and provide specific code examples to help readers better understand this area. In traditional front-end development, JavaScript, HTML, and CSS are often used to build user interfaces

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Django: A magical framework that can handle both front-end and back-end development! Django: A magical framework that can handle both front-end and back-end development! Jan 19, 2024 am 08:52 AM

Django: A magical framework that can handle both front-end and back-end development! Django is an efficient and scalable web application framework. It is able to support multiple web development models, including MVC and MTV, and can easily develop high-quality web applications. Django not only supports back-end development, but can also quickly build front-end interfaces and achieve flexible view display through template language. Django combines front-end development and back-end development into a seamless integration, so developers don’t have to specialize in learning

Questions frequently asked by front-end interviewers Questions frequently asked by front-end interviewers Mar 19, 2024 pm 02:24 PM

In front-end development interviews, common questions cover a wide range of topics, including HTML/CSS basics, JavaScript basics, frameworks and libraries, project experience, algorithms and data structures, performance optimization, cross-domain requests, front-end engineering, design patterns, and new technologies and trends. . Interviewer questions are designed to assess the candidate's technical skills, project experience, and understanding of industry trends. Therefore, candidates should be fully prepared in these areas to demonstrate their abilities and expertise.

See all articles