微信小程序:使用canvas 生成图片 并分享

废话不多说直接上代码!!!!

html

 <canvas canvas-id="positionPoster" style="width: 414px; height: 672px; margin: 0; padding: 0;" v-if="isCanvas"></canvas>

js

// 1、canvas对象 2、文本 3、X轴 4、Y轴 5、单行行高 6、文本的宽度
     */
    toFormateStr(ctx, str, axisX, axisY, titleHeight, maxWidth) {
      // 字体
      ctx.setFontSize(14 * this.rpx);
      // 颜色
      ctx.setFillStyle("#353535");
      // 文本处理
      let strArr = str.split("");
      let row = [];
      let temp = "";
      for (let i = 0; i < strArr.length; i++) {
        if (ctx.measureText(temp).width < maxWidth) {
          temp += strArr[i];
        } else {
          i--; //这里添加了i-- 是为了防止字符丢失,效果图中有对比
          row.push(temp);
          temp = "";
        }
      }
      row.push(temp); // row有多少项则就有多少行

      //如果数组长度大于2,现在只需要显示两行则只截取前两项,把第二行结尾设置成'...'
      if (row.length > 2) {
        let rowCut = row.slice(0, 2);
        let rowPart = rowCut[1];
        let test = "";
        let empty = [];
        for (let i = 0; i < rowPart.length; i++) {
          if (ctx.measureText(test).width < maxWidth) {
            test += rowPart[i];
          } else {
            break;
          }
        }
        empty.push(test);
        let group = empty[0] + "..."; //这里只显示两行,超出的用...表示
        rowCut.splice(1, 1, group);
        row = rowCut;
      }
      // 把文本绘制到画布中
      for (let i = 0; i < row.length; i++) {
        // 一次渲染一行
        ctx.fillText(row[i], axisX, axisY + i * titleHeight, maxWidth);
      }
      // // 保存当前画布状态
      // ctx.save();
      // // 将之前在绘图上下文中的描述(路径、变形、样式)画到 canvas 中。
      // ctx.draw();
    },
    //分享绘制
    shareImg() {
      this.isCanvas = true;
      wx.showLoading({
        title: "保存中...",
      });
      var that = this;
      let nickName = wx.getStorageSync("user")["nickName"];
      var context = wx.createCanvasContext("positionPoster");
      context.beginPath();

      context.fillStyle = "white";
      context.fillRect(0, 0, that.screenWidth, that.screenHeight);

      context.font = "14px sans-serif";
      context.fillStyle = "black";
      context.fillText(
        `${nickName}  推荐给你${that.detail.name}学院`,
        50,
        35,
        250
      );
      context.font = "14px sans-serif";
      context.fillStyle = "black";
      context.fillText(
        `已经有${that.detail.focusNum}个同学都在关注了`,
        50,
        65,
        250
      );

      context.font = "bold 16px sans-serif";
      context.fillStyle = "black";
      context.fillText(`${that.detail.name}`, 50, 100, 250);

      //绘制一个圆角矩形
      context.setStrokeStyle("black");
      context.strokeRect(50, 115, 150, 20);

      context.font = "14px sans-serif";
      context.fillStyle = "black";
      context.fillText(
        `${that.detail.stateRun},${that.detail.is211 ? "211" : ""},${
          that.detail.is985 ? "985" : ""
        },${that.detail.doubleFirstClass ? "双一流" : ""}`,
        55,
        130,
        150
      );
      context.font = "16px bold";
      context.fillText(`简介`, 50, 160, 70);
      //多行显示
      that.toFormateStr(context, that.detail.introduce, 50, 185, 24, 300);
      context.font = "14px sans-serif";
      context.fillStyle = "black";
      let y = 240;
      const y_text = 260;
      context.fillText(`成立时间`, 50, y, 100);

      context.font = "14px sans-serif";
      context.fillStyle = "black";
      context.fillText(`关注人数`, 170, y, 100);

      context.font = "14px sans-serif";
      context.fillStyle = "black";
      context.fillText(`报考人数`, 270, y, 130);

      context.font = "14px sans-serif";
      context.fillStyle = "black";
      context.fillText(
        `${that.detail.time ? that.detail.time : "--"}`,
        60,
        y_text,
        100
      );

      context.font = "14px sans-serif";
      context.fillStyle = "black";
      context.fillText(
        `${that.detail.focusNum ? that.detail.focusNum : "暂无"}`,
        180,
        y_text,
        100
      );

      context.font = "14px sans-serif";
      context.fillStyle = "black";
      context.fillText(
        `已有${that.detail.examNum ? that.detail.examNum + "人" : "暂无"}`,
        `${that.detail.examNum ? y_text : 305}`,
        y_text,
        130
      );
      //画图二维码
      context.drawImage(that.drImg, 80, 300, 250, 250);

      context.draw(false, function () {
        wx.canvasToTempFilePath({
          x: 0,
          y: 0,
          width: that.screenWidth,
          height: that.screenHeight,
          destWidth: that.screenWidth * that.pixelRatio, 
          destHeight: that.screenHeight * that.pixelRatio, 
          canvasId: "positionPoster",
          success: function (res) {
            that.saveImage = res.tempFilePath;
            if (!res.tempFilePath) {
              wx.showModal({
                title: "提示",
                content: "图片绘制中,请稍后重试",
                showCancel: false,
              });
            }
            //画板路径保存成功后,调用方法吧图片保存到用户相册
            wx.saveImageToPhotosAlbum({
              filePath: res.tempFilePath,
              //保存成功失败之后,都要隐藏画板,否则影响界面显示。
              success: (res) => {
                wx.hideLoading();
                that.isShow = false;
                that.isCanvas = false;
                Toast.success({ message: "保存成功!" });
              },
              fail: (err) => {
                console.log(err);
                wx.hideLoading();
                that.isShow = false;
                that.isCanvas = false;
              },
            });
          },
          fail: (res) => {
            wx.hideLoading();
            that.isShow = false;
            console.log(res);
          },
        });
      });
    },

最终效果图

 

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值