微信小程序拍照后对照片加水印

wxml
 

<view class="canvas-box">   

<canvas style="width: 375px;height: 667px;position:fixed;top:9999px" canvas-id="mycanvas" />

</view>

js
 

 // 选择图片
    chooseImage: function (e) {
        console.log('选择图片chooseImage')
        var that = this;
        wx.chooseImage({
            count: that.data.count, // 默认9
            sizeType: ['compressed'], // 可以指定是原图还是压缩图,默认二者都有
            sourceType: ['camera'], // 可以指定来源是相册还是相机,默认二者都有
            success: function (res) {
                that.addTimeWatermark(res.tempFilePaths[0])
            },
        })
    },
    // 添加时间水印
    addTimeWatermark: function (imagePath) {
        var that = this
        console.log('addTimeWatermark=' + imagePath)
        var ctx = wx.createCanvasContext('mycanvas');
        this.roundRectColor(ctx, 0, 30, 375, 620, 16);
        ctx.drawImage(imagePath, 15, 120, 344, 400);
        ctx.save();

        // 设置水印文字
        const time = app.util.formatTime()
        console.log('time=' + time)
        ctx.beginPath(); //开始绘制   
        ctx.setFontSize(22);
        ctx.setFillStyle('#DC3545')
        ctx.fillText(time, 15, 580); // 根据实际情况调整位置
        ctx.draw();

        //将生成好的图片保存到本地,需要延迟一会,绘制期间耗时
        setTimeout(function () {
            wx.canvasToTempFilePath({
                canvasId: 'mycanvas',
                success: function (res) {
                    var tempFilePath = res.tempFilePath;
                    console.log('imagePath=' + tempFilePath)
                    that.data.images.push(tempFilePath);
                    console.log(that.data.images)
                    that.setData({
                        imagePath: tempFilePath,
                    });

                },
                fail: function (res) {
                    console.log(res);
                }
            });
        }, 200);

    },
    roundRectColor: function (context, x, y, w, h, r) { //绘制圆角矩形(纯色填充)
        context.save();
        context.setFillStyle("#FFFFFF"); //小框
        context.setStrokeStyle('#FFFFFF') //大框
        // context.setLineJoin('round'); //交点设置成圆角
        context.setLineWidth(r);
        context.strokeRect(x + r / 2, y + r / 2, w - r, h - r);
        context.fillRect(x + r, y + r, w - r * 2, h - r);
        context.stroke();
        context.closePath();
    },

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值