这是一个小程序的公共组件,直接上代码:
index.js
// components/watermark/index.js
// 因为安全原因 svg 需转译以便作为背景图使用,也可直接在浏览器中打开
// 因为要保留 xvg 可读性,所以使用自定义方法进行转义
const svgToUrl = str => {
return `data:image/svg+xml,${str
.replace(/\n/g, '')
.replace(/<!--(.*)-->/g, '') // 必须去掉注释
.replace(/[\r\n]/g, ' ') // 最好去掉换行
.replace(/"/g, "'") // 单引号是保留字符,双引号改成单引号减少编码
.replace(/%/g, '%25')
.replace(/&/g, '%26')
.replace(/#/g, '%23')
.replace(/{/g, '%7B')
.replace(/}/g, '%7D')
.replace(/</g, '%3C')
.replace(/>/g, '%3E')}`;
};
/**
* 生成 svg 字符串
* @param {object} options 参数
* text 水印文字
* <text> 属性(x y transform) 方向位置按需调整
* <svg> 中fill属性决定字体颜色
*/
const getCanvasUrl = (options, user) => {
const {
text = `${new Date().toLocaleDateString()} ${user.name || ''}`,
width = 187.5,
height = 112.5,
fontSize = 16,
color = 'rgb(128,128,128)',
fontFamily = 'inherit',
} = options || {};
return `<svg
width="${width}"
height="${height}"
fill="${color}"
xmlns="http://www.w3.org/2000/svg"
>
<text
x="65%"
y="55%"
transform="rotate(-31, 100 100)"
font-size="${fontSize}"
font-family="${fontFamily}"
text-anchor="middle"
dominant-baseline="middle"
>${text}</text>
<text
x="65%"
y="55%"
transform="rotate(-31, 140 100)"
font-size="13"
font-family="${fontFamily}"
text-anchor="middle"
dominant-baseline="middle"
>${user.idCard || ''}</text>
</svg>`;
};
Component({
/**
* 组件的属性列表
*/
properties: {},
/**
* 组件的初始数据
*/
data: {},
ready() {
let user = {
name:'*******',
idcard:'***************************'
};
if (userProp.name) {
this.setData({
watermarkBck: `background: url("${svgToUrl(getCanvasUrl(null, user))}") repeat`,
})
}
},
})
index.wxml:
<view style="{{'width:100%;height:100%;position:fixed;top:0;left:0;z-index: 9999;pointer-events:none;opacity:0.2;' + watermarkBck}}" />
index.wxss:空
index.json
{
"component": true,
"usingComponents": {}
}

注:这个js核心代码部分是我再语雀看见的。感谢他
这篇博客介绍了如何在微信小程序中创建一个公共组件,用于生成并显示带有旋转文字和用户信息的SVG水印。通过将SVG转换为背景图片,并应用到组件样式中,实现了水印的全屏固定展示。关键代码包括`svgToUrl`函数用于转义SVG字符串,以及`getCanvasUrl`函数用于生成SVG内容。此组件适用于需要在页面上添加透明水印的应用场景。
&spm=1001.2101.3001.5002&articleId=121975714&d=1&t=3&u=6af6919ca390444f8d77bea0253cd692)
9899

被折叠的 条评论
为什么被折叠?



