WeApp – 小程序自定义文字水印组件

2022-12-08 263 0

预览效果

代码

// components/text-watermark/index.js
Component({
  options: {
    multipleSlots: true // 在组件定义时的选项中启用多slot支持
  },
  properties: {
    /** 文字颜色 */
    color: {
      type: String,
      value: '#eeeeee',
    },
    /** 文字大小 */
    fontSize: {
      type: Number,
      value: 22
    },
    /** 节点样式 */
    styles: {
      type: String,
      value: '',
    },
    /** 内容文案 */
    text: {
      type: String,
      value: ''
    },
    /** 是否容器定位 */
    isFixed: {
      type: Boolean,
      value: false,
    },
  },
  lifetimes: {
    ready() {
      // let phone = '13334567890';
      // const text = phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
      this.createImage(this.properties.text);
    },
  },
  data: {
    markUrl: '',
  },
  methods: {
    createImage(text) {
      const { color, fontSize = 22 } = this.properties;
      const { markUrl } = this.data;
      if (!text || markUrl) return;
      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')}`;
      };
      this.setData({
        markUrl: "--markUrl:url('" + svgToUrl(
          `<svg version="1.2" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 100"><style>.text{fill:${color};font-size:${fontSize}px;}</style><text class="text" style="transform: matrix(.92,-0.25,.3,1,0,80)">${text}</text></svg>`,
        ) + "')",
      });
    }
  }
})

// components/text-watermark/index.wxml
<view class="water-mark-mask {{isFixed?'fixed':''}}" style="{{markUrl}};{{styles}}">
    <view wx:if="{{markUrl}}" class="bg"></view>
</view>
/** components/text-watermark/index.wxss */
.water-mark-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 1;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  /* 无视鼠标事件,相当于鼠标事件透传下去一样 */
  pointer-events: none;
  flex: 1;
  font-size: 22rpx;
  overflow: hidden;
}

.water-mark-mask.fixed {
  position: fixed;
  top: 0;
  bottom: 0;
}
.water-mark-mask.fixed .bg {
  background-position: center left;
}
.water-mark-mask .bg {
  background: var(--markUrl);
  /* 根据内容调整尺寸 */
  background-size: 220rpx 100rpx;
  background-position: top left;
  width: 100%;
  height: 100%;
}

相关文章

JSUtils – 自定义EventEmitter
Video – 标签四周出现黑色边框问题
WeApp – 小程序Video组件真机下底部出现黑边
Typescript – Error: Cannot find module ‘@/xxx’ 找不到模块
WeApp – 真机scroll-view 中设置border-radius无效?
Demo – 老虎机抽奖(H5)

发布评论