背景
作为一个和金融相挂钩的平台,在项目中经常会用到给一些页面加上水印的需求
实现
//Watermark -- 水印
export default function watermark({
waterMark = "N",
width = "300px",
height = "300px",
textAlign = "center",
textBaseline = "middle",
font = "18px PingFang-SC-Medium",
fillStyle = "rgba(255,255,255,0.05)",
content = [""],
rotate = "-10",
zIndex = 9999,
} = {}) {
if (waterMark !== "Y") {
return {};
}
const canvas = document.createElement("canvas");
canvas.setAttribute("width", width);
canvas.setAttribute("height", height);
const ctx = canvas.getContext("2d");
const rotateValue = rotate;
ctx.textAlign = textAlign;
ctx.textBaseline = textBaseline;
ctx.font = font;
ctx.fillStyle = fillStyle;
ctx.rotate((Math.PI / 180) * rotateValue);
let i = 0;
content.forEach((item) => {
ctx.fillText(
item,
parseFloat(width) / 2,
parseFloat(height) / 2 + i++ * 20
);
});
const base64Url = canvas.toDataURL();
return {
position: "absolute",
top: 0,
left: 0,
width: "100%",
height: "100%",
zIndex: zIndex,
pointerEvents: "none",
backgroundRepeat: "repeat",
backgroundImage: `url('${base64Url}')`,
};
}
从上面代码可以看到,水印的核心还是通过canvas绘制,然后将绘制的内容转成base64格式图片,通过样式控制其是否平铺重复展示。
使用
import React from "react";
import watermark from "./common/waterMark";
import moment from "moment";
const styleStr = watermark({
waterMark: "Y",
content: ['React', moment().format("YYYY-MM-DD HH:mm:ss")],
fillStyle: 'greenyellow',
});
export default function App() {
return <div style={styleStr}></div>;
}