场景
本文介绍的是给已有的canvas添加水印的方法,主要使用场景是给导出的pdf或图片添加水印
代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<canvas id="test" width="1400" height="800"></canvas>
<script>
function getWaterMarker(text) {
const can = document.createElement("canvas");
const width = 360;
const height = 240;
Object.assign(can, { width, height });
const cans = can.getContext("2d");
if (cans) {
cans.rotate((-20 * Math.PI) / 120);
cans.font = "14px Vedana";
cans.fillStyle = "rgba(0, 0, 0, 0.15)";
cans.textAlign = "left";
cans.textBaseline = "middle";
if (!Array.isArray(text)) {
text = [text];
}
text.forEach((t, i) => {
cans.fillText(t, width / 20, height + i * 20);
});
}
return can;
}
function canvasAddWaterMarker(can, text) {
const { width, height } = can;
const ctx = can.getContext("2d");
if (ctx) {
const pat = ctx.createPattern(getWaterMarker(text), "repeat");
ctx.fillStyle = pat;
ctx.fillRect(0, 0, width, height);
}
}
// 使用示例
canvasAddWaterMarker(document.getElementById("test"), [
`用户名/${new Date()}`,
"内部文件,禁止外传",
]);
</script>
</body>
</html>
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。