In web development, watermarks are a commonly used method to protect content. By adding a watermark, it can effectively prevent unauthorized users from stealing content. This article will introduce how to add watermarks to elements through custom directives and implement anti-theft functionality.
Implementation Idea#
-
Generate Watermark Image Using Canvas:
- First, we create a
canvas
element and set its size according to the dimensions of the target element. - Use the
fillText
method ofCanvasRenderingContext2D
to draw the watermark text on the canvas. - By adjusting the tilt angle and spacing of the watermark, a more flexible watermark effect can be achieved.
- First, we create a
-
Set the Generated Image as Background:
- Convert the canvas content to a Base64 formatted image using
canvas.toDataURL("image/png")
and set it as the background of the target element.
- Convert the canvas content to a Base64 formatted image using
-
Use MutationObserver to Monitor DOM Changes:
- To prevent users from removing the watermark by modifying the DOM, we use
MutationObserver
to monitor changes to the attributes of the target element. - Once an attribute change (such as
style
orid
) is detected, we will restore the watermark settings.
- To prevent users from removing the watermark by modifying the DOM, we use
-
Anti-theft Functionality:
- By listening to changes in the DOM, we ensure that the watermark always exists in the target element, enhancing content protection.
Specific Implementation Code#
Here is the TypeScript code to implement the watermark functionality:
/**
* @param text Watermark text
* @param font Watermark font
* @param color Watermark color
* @param deg Watermark tilt angle, negative for uphill and positive for downhill
* @param gap Spacing between two adjacent watermarks
*/
const config = {
attributes: true,
attributeOldValue: true,
attributeFilter: ["class", "id", "style"],
characterData: true,
childList: true,
subtree: true,
characterDataOldValue: true,
};
function addWaterfall(
el,
{
text = "I am a watermark",
font = "bold 18px STHeiti",
color = "rgba(180,180,180,0.8)",
deg = -30,
gap = 200,
}
) {
const ob = new MutationObserver(changeOb);
function beginWatch() {
ob.observe(el, config);
}
function stopWatch() {
ob.disconnect();
}
function changeOb(mutationList) {
stopWatch();
console.log("DOM modified");
mutationList.forEach((mutation) => {
switch (mutation.type) {
case "attributes": {
const attr = mutation.attributeName;
if (attr === "style") {
mutation.target.style = mutation.oldValue;
} else if (attr === "id") {
mutation.target.id = mutation.oldValue;
}
}
}
});
beginWatch();
}
function createWaterfall() {
stopWatch();
const box_w = parseFloat(document.defaultView.getComputedStyle(el).width);
const box_h = parseFloat(document.defaultView.getComputedStyle(el).height);
const canvas = document.createElement("canvas");
canvas.id = "canvas";
canvas.width = box_w;
canvas.height = box_h;
const ctx = canvas.getContext("2d");
ctx.rotate((deg * Math.PI) / 180);
ctx.font = font;
ctx.fillStyle = color;
ctx.textBaseline = "middle";
const MAX_NUM = parseInt(Math.max(box_w, box_h) / gap) + 1;
const LEFT = Math.floor((MAX_NUM / Math.sqrt(2)) * -1);
const RIGHT = Math.ceil(MAX_NUM + MAX_NUM / Math.sqrt(2));
for (let i = LEFT; i <= RIGHT; i++) {
for (let j = LEFT; j <= RIGHT; j++) {
ctx.fillText(text, gap * i, gap * j);
}
}
el.style.background = `url(${canvas.toDataURL("image/png")})`;
beginWatch();
}
return createWaterfall;
}
export default addWaterfall;
Usage Example#
<div v-waterfall="{ text: 'This is a watermark', }" </div>
Summary#
Through the above methods, we can easily add watermarks to web elements and achieve a certain degree of anti-theft protection. This method is not only simple and easy to use but also highly flexible, allowing adjustments to the watermark's style and position according to needs. I hope this article can help you implement watermark functionality in your projects.
This article is synchronized and updated by Mix Space to xLog. The original link is http://www.sroxck.top/posts/fontend/waterfall