小程序背景水印文字组件。
watermark.js
Component({ /** * 组件属性列表 */ properties:{ text: { type:String, value:'' }, /*水印字体内容 可以自己调整*/ rotate: { type:Number, value:0 }, /*旋转 可以自己调整*/ fontSize:{ type:Number, value:25 }, color:{ type:String, value:'rgba(169, 169, 169, .2)' }, textAlign:{ type:String, value:'center' }, textBaseLine:{ type:String, value:'middle' }, width:{ type:Number, value:150 }, height:{ type:Number, value:200 }, lineHeight:{ type:Number, value:20 }, gap:{ type:Number, value:10 }, z_Index:{ type:Number, value:9999 }, pointer_events:{ type:String, value:'none' } }, /** * 页面的初始数据 */ data: { watermarkText:'', backgroundImage:'', zIndex:9999, pointerEvents:'none' }, /** * 组件生命周期声明对象,组件的生命周期:created、attached、ready、moved、detached * 将收归到 lifetimes 字段内进行声明 * 原有声明方式仍然有效,如同时存在两种声明方式 * 则 lifetimes 字段内声明方式优先级最高 */ lifetimes: { attached(){ this.setData({ watermarkText:this.properties.text, zIndex:this.properties.z_Index, pointerEvents:this.properties.pointer_events }) }, ready(){ this.generate(); } }, /** * 组件的方法列表 */ methods:{ generate() { this.setData({ backgroundImage: this.generateWatermark({ text:this.properties.text, rotate:this.properties.rotate, fontSize:this.properties.fontSize, color:this.properties.color, textAlign:this.properties.textAlign, textBaseLine:this.properties.textBaseLine, width:this.properties.width, height:this.properties.height }) }) }, generateWatermark(options = []) { //console.log(options); const{ text, rotate, fontSize, color, textAlign, textBaseLine, width, height } = options const canvas = wx.createOffscreenCanvas({ type:'2d', width, height }); const ctx = canvas.getContext('2d'); //清空画布 ctx.clearRect(0, 0, width, height) //文字样式 //ctx.font = ` ${fontSize}px Arial`; ctx.font = `normal ${fontSize}px Arial`; ctx.fillStyle = color; ctx.textAlign = textAlign; ctx.textBaseline = textBaseLine; //旋转中心点 ctx.translate(width/2, height/2); ctx.rotate(Math.PI/180 * rotate); ctx.translate(-width/2, -height/2); //绘制文字 //分割文本行 const lines = text.split("\n") || [] lines.forEach((line, index)=>{ ctx.fillText(line, width/2, height/2 + (index*this.properties.lineHeight)) }); return canvas.toDataURL(); } } })
watermark.wxml
<view class="watermark" style="pointer-events: {{pointerEvents}};z-index: {{zIndex}};background-image:url({{backgroundImage}});"></view>
watermark.wxss
.watermark{
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
width: 100%;
height: 100%;
background-repeat: repeat;
background-position: 0 0;
}
使用方法:
页面json 中 引用
"usingComponents": {
"watermark": "../../../components/watermark/watermark"
}
页面wxml引用代码:
<watermark text='水印文字' rotate='-50' fontSize='25'></watermark>
浙公网安备 33010602011771号