在前端页面中添加水印可以通过以下几种方法实现:
1. 使用 CSS 实现
使用 CSS 伪元素和 background
属性来添加水印。
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Watermark Example</title>
<style>
.watermarked {
position: relative;
}
.watermarked::before {
content: "Watermark";
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%) rotate(-30deg);
font-size: 3rem;
color: rgba(0, 0, 0, 0.1);
pointer-events: none;
z-index: 1000;
}
</style>
</head>
<body>
<div class="watermarked">
<!-- Your content here -->
<p>Some content with a watermark.</p>
</div>
</body>
</html>
2. 使用 Canvas
通过在 canvas
上绘制水印来实现。
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Canvas Watermark Example</title>
</head>
<body>
<canvas id="watermarkCanvas" width="600" height="400"></canvas>
<script>
const canvas = document.getElementById("watermarkCanvas");
const ctx = canvas.getContext("2d");
// Draw background
ctx.fillStyle = "#fff";
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Draw watermark text
ctx.font = "48px Arial";
ctx.fillStyle = "rgba(0, 0, 0, 0.2)";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.save();
ctx.translate(canvas.width / 2, canvas.height / 2);
ctx.rotate(-Math.PI / 6);
ctx.fillText("Watermark", 0, 0);
ctx.restore();
</script>
</body>
</html>
3. 使用 HTML 的 background
属性
将水印作为背景图像设置到页面的某个容器上。
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Background Watermark Example</title>
<style>
.watermarked {
background-image: url("watermark.png");
background-repeat: no-repeat;
background-size: 200px 100px;
background-position: center;
}
</style>
</head>
<body>
<div class="watermarked">
<!-- Your content here -->
<p>Some content with a watermark.</p>
</div>
</body>
</html>
4. 使用 JavaScript 动态生成水印
通过 JavaScript 在 DOM 中添加水印元素。
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Dynamic Watermark Example</title>
<style>
.watermark {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
pointer-events: none;
z-index: 9999;
text-align: center;
font-size: 3rem;
color: rgba(0, 0, 0, 0.1);
transform: rotate(-30deg);
}
</style>
</head>
<body>
<div id="content">
<!-- Your content here -->
<p>Some content with a watermark.</p>
</div>
<script>
const watermark = document.createElement("div");
watermark.className = "watermark";
watermark.textContent = "Watermark";
document.body.appendChild(watermark);
</script>
</body>
</html>