const getUserAgent = function (ua) {
if (ua) {
return ua.toLowerCase();
}
return typeof window !== 'undefined' && navigator.userAgent ? navigator.userAgent.toLowerCase() : '';
};
const isWindow = function (userAgent) {
return !(/mobile/i.test(getUserAgent(userAgent)));
};
const isMac = function (userAgent) {
return /mac os/i.test(getUserAgent(userAgent));
};
const waterMark = (userId, realName) => {
if (!userId && !realName) return;
const _isWindow = isWindow(navigator?.userAgent);
const _isMac = isMac(navigator?.userAgent);
const getWater = (txt) => {
let _size = _size = [220, 80, 80, 40];
let canvas = document.createElement('canvas');
let _opacity = _isWindow && !_isMac ? 0.16 : 0.08; // 兼容windows上水印特别浅
canvas.width = _size[0];
canvas.height = _size[1];
let ctx = canvas.getContext('2d');
ctx.font = '14px monospace';
ctx.textAlign = 'center';
ctx.fillStyle = `rgba(0,0,0,${_opacity})`;
ctx.translate(_size[2], _size[3]);
ctx.rotate(-Math.PI / 8);
ctx.fillText(txt, 0, 0);
return canvas.toDataURL('image/png');
}
let _txt = realName ? `${userId} ${realName}` : userId;
let _water = getWater(_txt);
let _div = document.createElement('div');
_div.setAttribute('style', `
pointer-events: none;
width: 100vw;
height: 100vh;
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 10001;
background: url(${_water}) repeat;
`);
document.body.prepend(_div);
}
export default waterMark;