小程序页面加水印-封装水印组件

584 阅读1分钟

小程序页面加水印-封装水印组件

1.思路

canvas生成base64地址,页面元素使用。

2.涉及技术点

canvas // 画图,生成图片地址

css: pointer-events: none; // 元素直接穿透,不影响交互

3.代码

1.wxml

<view>
   <canvas type="2d" id="canvas" class="canvas" />
   <view class="waterMask" style="background-image:url('{{backgroundImg}}')"></view>
</view>

2.js

 data: {
    backgroundImg: ''
  },
  ready() {
    const query = wx.createSelectorQuery().in(this)
    query.select('#canvas')
      .fields({ node: true, size: true })
      .exec((res) => {
        const canvas = res[0].node
        const ctx = canvas.getContext('2d')
​
        const dpr = wx.getSystemInfoSync().pixelRatio
        canvas.width = res[0].width * dpr
        canvas.height = res[0].height * dpr
        ctx.scale(dpr, dpr)
        
        ctx.rotate(Math.PI / 40) // 旋转
        
        ctx.font = 'bold 14px Menlo'
        ctx.fillStyle = '#aaa'
        var canvasText = '水印文案'
        ctx.fillText(canvasText, 20, 10)
        ctx.fillText(canvasText, 190, 100)
      
        var url = canvas.toDataURL()
        // this.triggerEvent('urlLoaded', url)
        this.setData({
          backgroundImg: url
        })
      })

3.wxss

.canvas {
    position: fixed;
    left: -200%;
    width: 100%;
    height: 200px;
}
​
.waterMask {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    top: 0;
    margin: auto;
    background-size: 100%;
    width: 100%;
    z-index: 999;
    pointer-events: none;
    opacity: 0.7;
}
4.效果图