0
点赞
收藏
分享

微信扫一扫

基于uni-app的小程序给view加文字水印

12a597c01003 2022-02-14 阅读 29
<view :style="'background-image:url(' + srcUrl + ');background-size: ' + canvasWidth + 'px 80px;'"></view>

<canvas canvas-id="firstCanvas" :style="'width: ' + canvasWidth + 'px; height: 80px;visibility: hidden;position: absolute;top:-500px'"></canvas>
onLoad() {
    getBackImage().then(function(data){
        that.canvasWidth = data.width;
        that.srcUrl = data.url;
    })
}

// 制作水印图片
getBackImage() {
    let text1 = "文字一";
    let time = new Date;
    // 当天的月日时分
    let text2 = (time.getMonth() + 1) + "" + time.getDate() + "" + time.getHours() + "" + time.getMinutes();
    // 根据文字长短找到适合的宽度
    let width = text1.length > text2.length ? (text1.length * 12 + 40) : (text2.length * 12 + 40);
    let height = 80;
    var ctx = uni.createCanvasContext("firstCanvas");
    ctx.setFontSize(12); // 设置文字大小
    ctx.rotate((-20 * Math.PI) / 180) // 设置文字倾斜度
    ctx.setFillStyle("rgba(192, 192, 192, 0.3)"); // 设置文字颜色
    ctx.setTextBaseline('middle'); // 设置位置
    ctx.setTextAlign('left'); // 设置展示位置
    ctx.fillText(text1, 0, height); // 填充文字一
    ctx.fillText(text2, 0, height - 30); // 填充文字二
            
    return new Promise(function(resolve, reject){
        ctx.draw(false,()=>{
          uni.canvasToTempFilePath({
              x: 0,
              y: 0,
              width: width,
              height: height,
              destWidth: width * 4,
              destHeight: height * 4,
              canvasId: "firstCanvas",
              quality: 1,
              success: function(res) {
                let obj = {
                    width: width,
                    url: res.tempFilePath
                }
                resolve(obj);
              } 
          })
        });
    });
}
举报

相关推荐

0 条评论