在JavaScript页面中增加水印通常是通过CSS和HTML5的Canvas元素来实现的。以下是一些基础概念、优势、类型、应用场景以及实现方法:
以下是一个简单的示例代码,展示如何在页面上添加文字水印:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Watermark Example</title>
<style>
body {
position: relative;
}
.watermark {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
pointer-events: none; /* 让水印不影响页面的交互 */
z-index: 9999; /* 确保水印在最上层 */
}
.watermark canvas {
display: block;
}
</style>
</head>
<body>
<div class="watermark" id="watermark"></div>
<script>
function addWatermark(text) {
const watermarkDiv = document.getElementById('watermark');
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const width = window.innerWidth;
const height = window.innerHeight;
canvas.width = width;
canvas.height = height;
// 设置水印样式
ctx.globalAlpha = 0.1; // 透明度
ctx.font = '20px Arial'; // 字体大小和类型
ctx.fillStyle = '#000000'; // 字体颜色
ctx.rotate(-0.1); // 旋转角度
// 绘制水印
ctx.fillText(text, width / 2, height / 2);
// 将canvas添加到水印div中
watermarkDiv.appendChild(canvas);
// 监听窗口大小变化,重新绘制水印
window.addEventListener('resize', () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
ctx.clearRect(0, 0, width, height);
ctx.fillText(text, width / 2, height / 2);
});
}
// 添加水印
addWatermark('Confidential');
</script>
</body>
</html>
watermark
div的z-index
足够高。ctx.globalAlpha
的值来控制透明度。通过以上方法,你可以在JavaScript页面中灵活地添加水印,以满足不同的需求。
领取专属 10元无门槛券
手把手带您无忧上云