微信小程序 canvas使用过程中碰见的坑-制作海报并保存图片过程

废话不多说,先上效果图
在这里插入图片描述

1、首先第一个Canvas的使用,一般海报的制作全是点击触发海报制作,在此之前,肯定是想把画布隐藏,但是在使用“hidden”和“ display: none” 这两个属性时,在运行小程序,小程序获取不到画布的宽高,所以会报错。经过一段时间搜索,找到一种当前比较好用的办法就是,定位到屏幕以外进行隐藏

.wxss代码
.cover-back {
  width: 100vw;
  height: 100vh;
  background: rgba(0, 0, 0, .8);
  position: fixed;
  top: 0rpx;
}
.wxml代码
<view class="cover-back" style="left: {{numLeft}}px;">
  <view class="wrapper">
    <canvas type="2d" id="canvas_box" style="width:300px;height:470px"></canvas>
    <view class="canvas-icon" hidden="{{show}}">
      <view class="canvas-iconview" bindtap="onAgain">
        <view class="iconfont icon-zhongxuan canvas-again"></view>
        <view class="canvas-savetxt">重新选取</view>
      </view>
      <view class="canvas-iconview " bindtap="onSave">
        <view class="iconfont icon-xiazai1 canvas-save "></view>
        <view class="canvas-savetxt">保存到手机</view>
      </view>
    </view>
  </view>
</view>
.js代码
Page({
  data: {  
    nickname: "黑夜里的眼",
    headimg: '/images/head.jpg',
    tmpAvatarUrl: "../../images/tu1.jpg",//本地图片路径
    show: false,//保存按钮显示与否
    numLeft: 99999,//画布显示位置,根据你的需要,在进行显示和隐藏
    img_temp: "",//图片保存临时路径
  },
  }

2、第二步进行画布的制作
制作效果图这样的效果,需要几个过程。
第一步,制作把图片、头像、昵称等信息画到画布上面。
第二部,点击保存按钮,保存图片,在点击保存是,触发微信小程序访问用户相册授权功能,
1:授权成功,正常保存图片。
2:用户拒绝授权,引导用户设置可以访问。
/因为我是用的是Canvas 2D/,以下就围绕这个进行介绍,当前我是用的全是本地图片,网络图片需要转换一个,注释出就是网络图片,转换为本地临时图片方法

  //分享海报点击事件
  onShare: function (event) {
    ///网络图片转换为本地图片
    // wx.getImageInfo({
    //   src: canverimg,
    //   success: (res) => {
    //     that.setData({
    //       tmpAvatarUrl: res.path,
    //     })
    //   }
    // })
    var that = this;
    that.setData({
      numLeft: 0,//让画布图层显示到屏幕中间
    })
    var canverimg = "";//列表中图片路径
    var index = that.data.radioValue;
    var arrs = that.data.list;
    for (const x in arrs) {
      if (arrs[x].id == index) {
        canverimg = arrs[x].imageurl;
      }
    }
    that.setData({
      tmpAvatarUrl: canverimg,
    })

    wx.showLoading({
      title: '疯狂制作中...',
    })
    //海报制作
    const query = wx.createSelectorQuery();
    query.select('#canvas_box')
      .fields({
        id: true,
        node: true,
        size: true
      })
      .exec(this.init.bind(this));


  },
  //重新制作事件
  onAgain: function (event) {
    var that = this;
    that.setData({
      show: false,
      numLeft: 999999,
    })

  },
  //保存海报事件
  onSave: function (event) {
    var that = this;
    // 相册授权
    wx.getSetting({
      success(res) {
        // 进行授权检测,未授权则进行弹层授权
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success() {
              that.canvasToImage();
            },
            // 拒绝授权时,在下载按钮上面增加打开手机设置按钮
            fail() {
              wx.showModal({
                title: '温馨提示',
                content: '保存失败不能访问相册,去设置允许访问相册',
                confirmText: "去设置",
                success(res) {
                  if (res.confirm) {
                    wx.openSetting({
                      success(settingdata) {
                        if (settingdata.authSetting['scope.writePhotosAlbum']) {
                          that.canvasToImage(); //保存失败尝试再次保存
                        } else {
                          wx.showToast({
                            title: '设置失败',
                            icon: 'error',
                          })

                        }
                      }
                    })
                  }
                  else if (res.cancel) { }
                }
              })
            }
          })
        } else {
          that.canvasToImage();
        }
      },
      fail(res) {
        wx.showModal({
          title: '温馨提示',
          content: '未授权,请先授权',
          showCancel: false,
          success(res) { }
        })
      }
    })
  },
  //获取画布信息
   init(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);
    this.setData({
      canvas,
      ctx
    });
    ctx.save();
    ctx.arc(150, 235, 278, 0, 2 * Math.PI) //画出圆
    ctx.clip(); //裁剪上面的圆形
    ctx.fillStyle = "white";
    ctx.fill();
    ctx.restore();
    //向画布载入图片的方法,
    this.canvasDraw(ctx);
    this.name(ctx);
    this.code(ctx).then(rrr => {
      // 头像加载
      this.hande(ctx)
    })
    this.logo(ctx);
  },
  // 封面图
  canvasDraw(ctx) {
    let img = this.data.canvas.createImage(); //创建img对象
    img.src = this.data.tmpAvatarUrl;
    img.onload = () => {
      this.data.ctx.drawImage(img, 25, 25, 250, 346);//填充画布
      ctx.restore();
    };

  },
  // 头像
  hande(ctx) {
    let hande = this.data.canvas.createImage(); //创建img对象
    hande.src = "../../images/head.jpg";
    hande.onload = () => {
      //绘制头像图片
      ctx.beginPath();
      ctx.arc(60, 380, 30, 0, 2 * Math.PI) //画出圆   
      ctx.clip(); //裁剪上面的圆形
      ctx.fillStyle = "white";
      ctx.fill();
      ctx.beginPath();
      ctx.arc(60, 380, 20, 0, 2 * Math.PI) //画出圆   
      ctx.clip(); //裁剪上面的圆形
      ctx.fillStyle = "red";
      ctx.fill();
      ctx.drawImage(hande, 40, 360, 40, 40);
      ctx.restore();
    };

  },
  //logo
  logo(ctx) {
    let logo = this.data.canvas.createImage(); //创建img对象
    logo.src = "../../images/logo1.png";
    logo.onload = () => {
      ctx.drawImage(logo, 35, 420, 80, 30);
      if (logo.complete) {
        wx.hideLoading();
        this.data.show = true;
      }
    };

  },
  // 名字
  name(ctx) {
    ctx.fillStyle = "#333333";
    ctx.font = 'normal bold 12px sans-serif';
    ctx.fillText(this.data.nickname, 90, 400);
  },
  // 二维码
  code(ctx) {
    return new Promise(rrr => {
      let code = this.data.canvas.createImage(); //创建img对象
      code.onload = () => {
        this.data.ctx.drawImage(code, 200, 380, 70, 70);
      };
      code.src = "../../images/code.jpg";
      setTimeout(() => {
        rrr(true)
      }, 100);
    })
  },
  //海报转换为图片
  canvasToImage: function () {
    var that = this;
    wx.canvasToTempFilePath({
      x: 0,
      y: 0,
      width: 300,
      height: 470,
      quality: 1,
      fileType: 'jpg',
      canvas:that.data.canvas,
      success: function (res) {
        that.setData({
          img_temp: res.tempFilePath
        })
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success(res) {
            wx.showModal({
              title: '',
              content: '图片已保存到相册,赶紧晒一下吧',
              showCancel: false,
              confirmText: '好的',
              confirmColor: '#72B9C3',
              success: function (res) {
              }
            })
          },
        })
      },
      fail: function (res) {
        console.log(res)
      }
    }, this)
  }

以上就是海报的制作的整个过程,本人记作记录,也给其他人做个避坑指南借鉴。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值