钉钉小程序实现水印
背景
由于公司项目数据安全需要,要求在钉钉小程序的页面中需要加上包含用户姓名工号和一些警示语的水印,此文简要记述了实现过程。
与PC端实现水印的思路基本一致,都是借助 canvas 生成水印图片作为背景图,全凭覆盖页面即可。
canvas 生成水印图片
钉钉端的 canvas 使用方式与PC端略有不同,详细使用可参考文档:钉钉开放文档
首先,我们先办页面标签写好:
<div
style={
{
zIndex: 9,
position: "fixed",
width: "100vw",
pointerEvents: "none",
height: "100vh",
top: 0,
left: 0,
backgroundImage: `url(${img})`
}} >
</div>
<canvas width="200" height="200" style={{ display: "none" }} id="watermark"></canvas>
pointerEvents属性一定不能漏掉,他的作用是让水印元素不响应鼠标事件,可以避免水印元素遮挡页面元素导致页面其他点击事件无效
然后绘制水印内容:
const getBase64Background = async (realName, workId) => {
const position = { x: 50, y: 120 };
const text = `${realName}(${workId})`
//@ts-ignore
const context = dd.createCanvasContext('watermark');
if (context) {
context.setFontSize("40px");
context.setLineWidth(2);
context.rotate(-20 * Math.PI / 180);
context.setStrokeStyle('rgba(255, 255, 255, 0.2)');
context.setFillStyle("rgba(0, 0, 0, 0.2)");
context.setTextAlign('center');
context.setTextBaseline('hanging');
context.fillText(text, position.x, position.y);
context.fillText("自定义的提示信息", position.x, position.y + 15);
context.draw();
// 保存图片到临时路径
context.toTempFilePath({
success(res) {
console.log("success", res);
setImg(res.filePath)
},
fail(err) {
console.log("fail", err)
}
});
}
return null;
}
最后在合适的时机调用 getBase64Background 方法生成背景并设置到页面遮罩元素上即可。