/*
* EXAMPLE
* text 水印文字
* parentId 父级DOM节点ID 相对定位 可选 默认当前父级元素
* density 密度 上下 左右 默认 50 30
* styleObj 水印样式
* <Watermark parentId='#candidate_wrapper' density='50px 30px' styleObj={}/>
* */
// Watermark.js
import React, { useEffect, useRef } from "react";
import html2canvas from "html2canvas";
const default_style = {
position: "absolute",
left: "-100%",
top: "-100%",
transform: "rotate(-15deg)",
color: "rgba(0,0,0,.06)",
fontSize: "14px",
};
const observerOption = {
childList: true,
attributes: true,
subtree: true,
attributeFilter: ["style"],
attributeOldValue: true,
};
const watermarkCanvas = { current: null };
/**
* @return {boolean}
*/
function Watermark(props) {
const {
styleObj = default_style,
text = "我是水印",
parentId,
density = "50px 30px",
} = props;
const nodeRef = useRef();
const parentNodeRef = useRef();
useEffect(() => {
parentNodeRef.current = parentId
? document.querySelector(`#${parentId}`)
: nodeRef.current.parentNode;
parentNodeRef.current.style.backgroundAttachment = `fixed`;
parentNodeRef.current.style.backgroundPosition = `top center`;
if (watermarkCanvas.current) {
loadMark();
} else {
html2canvas(nodeRef.current, { scale: 1 }).then((canvas) => {
watermarkCanvas.current = canvas.toDataURL("image/png");
loadMark();
});
}
const MutationObserver =
window.MutationObserver ||
window.WebKitMutationObserver ||
window.MozMutationObserver;
const watermarkDom = new MutationObserver(observerCallback);
watermarkDom.observe(parentNodeRef.current, observerOption);
}, []);
const loadMark = () => {
if (watermarkCanvas.current) {
parentNodeRef.current.style.backgroundImage = `url(${watermarkCanvas.current})`;
}
};
const observerCallback = () => {
loadMark();
};
return watermarkCanvas.current ? (
<div ref={(watermarkText) => (nodeRef.current = watermarkText)} />
) : (
<div
style={{ ...styleObj, padding: density }}
ref={(watermarkText) => (nodeRef.current = watermarkText)}
>
{text}
</div>
);
}
export default Watermark;
import React from "react";
import Watermark from "@/components/public/Watermark/Watermark";
interface IUserInfo {
name: string;
englishName: string;
originId: number;
}
export interface IProps {
userInfo: IUserInfo;
}
const Index: React.FC<IProps> = props => {
const { userInfo } = props;
return (
<div>
<div>我是内容</div>
{userInfo.name && (
<Watermark
text={`${userInfo.name} ${userInfo.englishName} - ${userInfo.originId}`}
/>
)}
</div>
);
};
export default Index;