uniapp小程序使用canvas绘制内容并保存到本地相册

需求:根据不同用户自动生成对应证书,并且可以下载该证书(下载后得到的是一张图片),故要想实现该功能,则需要借助canvas将动态生成的内容绘制到页面中,然后再实现下载功能。

1.html代码

<view class="certify-main">
  <canvas type="2d" id="myCanvas" style="width: 375px; height: 550px;background-color: #fff;" />
  <view class="download" @click="download">下载证书</view>
</view>

页面很简单,只包含一个canvas和下载按钮即可。

2.js代码

// 所需数据
data() {
  return {
    name: "",
    year: "",
    month: "",
    day: "",
    beforeName: "",
    textCanvas: null,
    certificateNo:'',
    certQrCode:'', // 后台返回的二维码地址
  };
},

// 所需方法
methods(){
  // 从后台获取信息(以下代码我做了封装,你们直接正常请求接口获取数据就行,可以忽略)
  getCurrentOrg() {
    let opts = {
      url: url,  // url是接口地址
      method: "get",
    };
    let param = {}; // 参数
    request
      .httpTokenRequest(opts, param)
      .then((data) => {
        if (data && data.data && data.data.data) { 
          // 将获取到的数据赋值给对应字段
          const msg = data.data.data;
          if (msg.updateTime) {
            this.year = msg.updateTime.substring(0, 4)
            this.month = msg.updateTime.substring(5, 7)
            this.day = msg.updateTime.substring(8, 10)
          }
          this.beforeName = msg.snmsPrefix || "";
          this.name = msg.orgName;
          this.certificateNo = msg.certCode
          this.certQrCode = msg.certQrCode
          // 调用canvas绘制内容的方法
          this.drawCanvas()
        }
      })
      .catch((err) => {
        console.log(err);
        this.$refs.uToast.show({
          title: "数据异常或不存在",
          type: "warning",
          duration: "2300",
        });
      });
  },
  // 下载证书的方法
  download() {
    // 指定 this 指向
    let that = this;
    // 在微信中保存canvas为图片到本地,要通过canvas 实例的参数进行设置
    wx.canvasToTempFilePath({
      x: 0,
      y: 0,
      width: that.textCanvas.width, // 设置画布宽度
      height: that.textCanvas.height, // 设置画布高度
      destWidth: that.textCanvas.width, // 屏幕width像素密度设置
      destHeight: that.textCanvas.height, // 屏幕height像素密度设置
      canvas: that.textCanvas, // 这里是重点,获取实例的时候保存为全局变量就行了
      complete(res) {
        console.log(res);
        // res.tempFilePath 返回的是临时地址 png 或者 jpg
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success() {
            uni.showToast({
              title: "保存成功",
              icon: "success",
            });
          },
          fail() {
            uni.showToast({
              title: "保存失败",
              icon: "error",
            });
          },
        });
      },
    });
  },
  drawCanvas() {
    // 指定this的指向
    let that = this;
    // uni-app 中,不管是小程序,app,h5 在获取元素实例时,都是统一的方法,只要获取元素的宽高
    uni
      .createSelectorQuery()
      .select("#myCanvas")
      .fields({ node: true, size: true })
      .exec((res) => {
        console.log(res);
        // 获取设备设备像素比
        const dpr = uni.getSystemInfoSync().pixelRatio;
        // 微信小程序绘制
        let textCanvas = (that.textCanvas = res[0].node); // 获取元素实例
        textCanvas.width = res[0].width * dpr; // 设置canvas像素宽
        textCanvas.height = res[0].height * dpr; // 设置canvas像素高
        let textCtx = textCanvas.getContext("2d"); // 创建二维绘图
        textCtx.clearRect(0, 0, res[0].width, res[0].height); // 设置画布大小
        textCtx.beginPath(); // 创建一条新的路劲
        textCtx.scale(dpr, dpr); // 设置x,y缩放(这里作用不大,,没效果)
        // 这里开始绘制canvas内容,绘制的过程当中,不知道是小程序的问题,还是什么问题在绘制有背景图片的内容时,
        // 文字内容必须要延迟绘制,也就是要定时器延迟一定时间才能绘制,要不然就会将文字覆盖在图片下方。
        // 图片的绘制(这里将此图片作为背景图的,图片不能带底色,即透明的,方便在上面写字绘图)
        const tx = textCanvas.createImage();
        tx.src = "https://test.xxxx.com/pic/new_certify.png"; // 线上地址或者本地地址都可以
        tx.onload = () => {
          textCtx.drawImage(
            tx,
            5,
            20,
            res[0].width-10,
            res[0].height-20
          ); // 参数从左到右说明, 图片文件,x轴开始位置,y轴开始位置,x轴结束位置,y轴结束位置
        };
        // 文字设置
        textCtx.fillStyle = "#333"; // 文字颜色
        textCtx.font = "bold 12px MicrosoftYaHei"; // 字体样式 设置加粗("normal bold 16px sans-serif");
        textCtx.fillText(this.name, 102, 203); // 设置文字内容, x轴位置,y轴位置
        textCtx.fillText(this.year, 111, 230); // 设置文字内容, x轴位置,y轴位置
        textCtx.fillText(this.month, 180, 230); // 设置文字内容, x轴位置,y轴位置
        textCtx.fillText(this.day, 230, 230); // 设置文字内容, x轴位置,y轴位置
        textCtx.fillText(this.beforeName, 168, 296); // 设置文字内容, x轴位置,y轴位置
        textCtx.fillStyle = "#003E8A";
        textCtx.font = "10px MicrosoftYaHei";
        textCtx.fillText(this.certificateNo, 186, 466); // 设置文字内容, x轴位置,y轴位置
        // 二维码设置
        const tx1 = textCanvas.createImage();
        tx1.src = this.certQrCode
        tx1.onload = () => {
          textCtx.drawImage(
            tx1,
            154,
            380,
            65,
            65
          ); // 参数从左到右说明, 图片文件,x轴开始位置,y轴开始位置,x轴结束位置,y轴结束位置
        };
      });
  },
}

3.效果图展示

注:下图证书编号这个地方的样式忘了修改,部分信息由于涉及项目隐私,故马赛克,但不影响整体效果(其中黑色文字+二维码+证书编号是动态的,其余文字都是背景图自带的)

 

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
uniapp小程序中,使用canvas涂鸦实现撤销和恢复上一步的功能,可以采用类似于原生小程序的方式进行操作。以下是示例代码: ```vue <template> <canvas class="canvas" canvas-id="myCanvas" @touchstart="touchStart" @touchmove="touchMove" @touchend="touchEnd"></canvas> <view class="tools"> <button class="btn" @tap="undo">撤销</button> <button class="btn" @tap="redo">恢复</button> </view> </template> <script> export default { data() { return { ctx: null, // canvas绘图上下文 startX: 0, // 起始x坐标 startY: 0, // 起始y坐标 drawData: [], // 绘制数据 index: 0 // 当前绘制步骤 } }, mounted() { // 获取canvas绘图上下文 let query = uni.createSelectorQuery().in(this) query.select('.canvas').fields({node: true, size: true}).exec((res) => { let canvas = res[0].node this.ctx = canvas.getContext('2d') }) }, methods: { // 监听touchstart事件 touchStart(e) { this.startX = e.touches[0].clientX this.startY = e.touches[0].clientY // 绘制起始点 this.ctx.beginPath() this.ctx.moveTo(this.startX, this.startY) // 将绘制数据添加到数组中 this.drawData.splice(this.index, this.drawData.length - this.index, { type: 'start', x: this.startX, y: this.startY }) this.index++ }, // 监听touchmove事件 touchMove(e) { let currentX = e.touches[0].clientX let currentY = e.touches[0].clientY // 绘制线条 this.ctx.lineTo(currentX, currentY) this.ctx.stroke() // 将绘制数据添加到数组中 this.drawData.splice(this.index, this.drawData.length - this.index, { type: 'move', x: currentX, y: currentY }) this.index++ }, // 监听touchend事件 touchEnd(e) { // 将绘制数据添加到数组中 this.drawData.splice(this.index, this.drawData.length - this.index, { type: 'end' }) this.index++ }, // 撤销操作 undo() { // 判断是否有可撤销的绘制步骤 if(this.index > 0) { this.index-- // 判断绘制数据类型 while(this.index > 0 && this.drawData[this.index - 1].type !== 'start') { this.index-- } // 重新绘制整个canvas this.redraw() } }, // 恢复上一步操作 redo() { // 判断是否有可恢复的绘制步骤 if(this.index < this.drawData.length) { // 判断绘制数据类型 while(this.index < this.drawData.length && this.drawData[this.index].type !== 'end') { this.index++ } this.index++ // 重新绘制整个canvas this.redraw() } }, // 重新绘制整个canvas redraw() { // 清空canvas this.ctx.clearRect(0, 0, uni.upx2px(750), uni.upx2px(1000)) // 循环绘制数据,重新绘制整个canvas for(let i = 0; i < this.index; i++) { let data = this.drawData[i] if(data.type === 'start') { // 绘制起始点 this.ctx.beginPath() this.ctx.moveTo(data.x, data.y) } else if(data.type === 'move') { // 绘制线条 this.ctx.lineTo(data.x, data.y) this.ctx.stroke() } } } } } </script> <style> .canvas { width: 750upx; height: 1000upx; background-color: #fff; } .tools { display: flex; justify-content: space-around; margin-top: 20upx; } .btn { width: 200upx; height: 80upx; line-height: 80upx; text-align: center; font-size: 32upx; color: #fff; background-color: #f00; border-radius: 40upx; } </style> ``` 以上代码中,使用canvas的touchstart、touchmove和touchend事件来监听用户的绘制操作,并将绘制数据存储到数组中。同时,还定义了撤销和恢复上一步操作的方法,并通过重新绘制整个canvas来实现撤销和恢复上一步操作的效果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值