小程序

小程序图片添加文字水印

2022-07-11  本文已影响0人  秀萝卜

公司需求:小程序上传图片,添加文字水印
完成经过:一堆坑

1.官方文档
官方文档地址如下:
https://developers.weixin.qq.com/miniprogram/dev/component/canvas.html
小程序有两种canvas写法,可不要搞混了
2.获取图片宽高

小程序添加文字,需要使用canvas重新绘制canvas图片,需要设定宽高。
wx.getImageInfo获取原始图片宽高

    getInfo() {
        wx.getImageInfo({
            src: this.data.url, 
            success(res) {
                console.log(res.path)//可以获取图片路径,图片长宽等信息
            }
        })
    }
3.不能使用线上url,只能使用本地临时图片路径
使用canvas的时候,如果是线上url会报错,必须使用临时图片路径(tempUrl),
格式如下:
http://tmp/dLBG6wXVqhdBca99922121344e8d69bad5aa34f404ea.png
获取办法:
使用wx.getImageInfo方法,无论src是临时图片路径还是线上url,都返回临时图片路径
4.canvas基本用法
  <!-- type有两种,必须写-->
  <canvas type="2d" id="myCanvas"></canvas>
const query = wx.createSelectorQuery()
    query.select('#myCanvas')
      .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.fillRect(0, 0, 100, 100)
      })
5.canvas转为图片
transferCanvasToImage(canvas) {
        const that = this;
        wx.canvasToTempFilePath({
            canvas: canvas,
            success(res) {
                console.log('canvas分享图片地址', res.tempFilePath)
                var src = res.tempFilePath
                that.setData({
                    src
                })
            }
      })
 },
6.隐藏canvas不显示

公司需求:隐藏掉canvas不显示,但是可以使用。
结果:不能用使用wx:if和display:none,我没有找到好的办法,最后只能在外面加一层

<view>
    <view wx:if="{{canvasImg}}">
        <image src="{{canvasImg}}" mode="widthFix" style="width:750rpx"></image>
    </view>
    <view style='width:0rpx;height:0rpx;overflow:hidden;'>
        <canvas id='canvasId' type="2d" style="position:fixed;left:9999px"></canvas>
    </view>
</view>
7.demo核心代码
<view>
    <view wx:if="{{canvasImg}}">
        <image src="{{canvasImg}}" mode="widthFix" style="width:750rpx"></image>
    </view>
    <view style='width:0rpx;height:0rpx;overflow:hidden;'>
        <canvas id='canvasId' type="2d" style="position:fixed;left:9999px"></canvas>
    </view>
</view>
Page({
    data: {
        img: 'https://inews.gtimg.com/newsapp_bt/0/15084535902/1000',
        canvasImg: '',//生成的canvasImg
        canvasId: 'canvasId',
    },
    onLoad() {
        this.getCanvas()
    },
    getCanvas() {
        var mycenter = 0 //文字左右居中显示
        var myheight = 0 //文字高度
        const that = this
        const query = wx.createSelectorQuery();
        query.select('#' + this.data.canvasId).fields({ node: true, size: true }).exec((res) => {
            console.log(res)
            const canvas = res[0].node;
            const ctx = canvas.getContext('2d')
            new Promise(function (resolve) {
                // 绘制背景图片
                wx.getImageInfo({
                    src: that.data.img, //网络图片,如果不行请换一个
                    success(res) {
                        console.log(res)
                        var width = res.width
                        var height = res.height
                        mycenter = width / 2
                        myheight = height
                        canvas.width = width
                        canvas.height = height
                        const img = canvas.createImage();
                        img.src = res.path;
                        img.onload = () => {
                            ctx.drawImage(img, 0, 0, width, height);
                            resolve(true);
                        }
                    }
                })
            }).then(() => {
                ctx.font = "500 32px Arial";
                ctx.textAlign = 'center'
                ctx.fillStyle = 'white';
                ctx.fillText('adakfjlkawdjfklasjfklasjf', mycenter, myheight - 50)
            }).then(function () {
                that.transferCanvasToImage(canvas)
            }).catch((err) => { })
        })
    },
//canvas转为图片
    transferCanvasToImage(canvas) {
        const that = this;
        wx.canvasToTempFilePath({
            canvas: canvas,
            success(res) {
                that.setData({
                    canvasImg: res.tempFilePath
                })
                console.log(that.data.canvasImg)
            }
        })
    },
})

参考资料:
1.官方文档
https://developers.weixin.qq.com/miniprogram/dev/component/canvas.html

  1. https://blog.csdn.net/qq_33769914/article/details/125148615
  2. https://jishuin.proginn.com/p/763bfbd5f828
上一篇下一篇

猜你喜欢

热点阅读