微信小程序canvas绘图运用案例总结

一、canvas建议使用hidden进行隐藏或者显示

如实使用wx:if 无法在原canvas进行第二次绘图

<view style="padding:30px 0;" hidden="{{custem_space.canvarsta}}">
  <canvas canvas-id='space_img' style='width:{{custem_space.canvas_w}};height:{{custem_space.canvas_h}};'></canvas> 
</view>

二、canvas的高度可以在draw之前进行修改正到合适高度

三、绘图网络图片时注意以下问题:

(一)添加设置:
在开发者后台,找到开发–》服务器域名管理,在其添加网络图片的域名地址
(二)刷新配置
添加完域名地址之后,在开发者工具右侧详情-》项目配置-》刷新配置
(三)使用网络地址
完成设置,这样小程序才能合法下载和绘图网络图片
(四)使用案例:wx.downloadFile()

wx.downloadFile({
      url: '网络图片地址',
      success: res => {
        if (res.statusCode === 200) {
          console.log('下载成功')
          //图片成功下载到本地,使用此图片地址进行绘制
           var imgUrl = res.tempFilePath;
        }
      },
      fail: res => {
        console.log('下载失败')
      }
});

四、注意图片对设备的适配性

(一)根据宽度设置画布高度
(二)根据宽度元素尺寸
(三)最重要:canvas画布一定要比设备尺寸大2倍,否则,有些设备图片会出现锯齿

wx.getSystemInfo({
      success: res => {
         //画布一定要比设备尺寸大2倍
        var custem_space = that.data.custem_space;
         var canvas_w = res.screenWidth * 2;
		 var canvas_h = canvas_w * 2;
		 custem_space.canvas_w = canvas_w +"px";
		 custem_space.canvas_h = canvas_h +"px";
        that.setData({
          custem_space: custem_space
        });
		 
		 //设置画图信息
		 var unit = res.screenWidth / 375;
		 var pace_img_top = "../../images/pace_img_top.png";
		 var ctx = wx.createCanvasContext('space_img');
		 //顶部图片
		 ctx.drawImage(pace_img_top, 0, 0, unit * 375, unit * 107);
    }
})

五、绘制圆形头像

ctx.save();
 ctx.beginPath();
 ctx.arc(unit * 318, unit * 44, unit * 16, 0, unit * Math.PI * 2, false);
 ctx.clip();
 ctx.drawImage(userimg, unit * 300, unit * 24, unit * 36, unit * 36);
 ctx.restore();

六、ctx.draw()之后图片不完整或者偏离问题

(一)ctx.draw完之后有个回调函数,因为小米和华为手机兼容问题,需要过一段时间(测试1秒后正常)再使用wx.canvasToTempFilePath(),否则会出现绘制不完整或则偏离正常位置的情况

ctx.draw(false, function () {
      setTimeout(function () { 
          wx.canvasToTempFilePath({})
    },2000)
})

完整案例展示

 //获取用户设备信息,屏幕宽度
wx.getSystemInfo({
      success: res => {
         //canvas画布一定要比设备尺寸大2倍
         var custem_space = that.data.custem_space;
         var canvas_w = res.screenWidth * 2;
		 var canvas_h = canvas_w * 2;
		 custem_space.canvas_w = canvas_w +"px";
		 custem_space.canvas_h = canvas_h +"px";
         that.setData({
            custem_space: custem_space
         });

        //设置画图信息
        var unit = canvas_w  / 375;
        var pace_img_top = "../../images/pace_img_top.png";
        var xcx_ewm = "../../images/xcx_ewm.png";
        var userimg = "../../images/userimg.png";
        var ctx = wx.createCanvasContext('space_img');

        //设置画布背景
        ctx.fillStyle = "#FFFFFF";
        ctx.fillRect(0, 0,canvas_w, canvas_h);
        //顶部图片
        ctx.drawImage(pace_img_top, 0, 0, unit * 375, unit * 107);
        //顶部文案
        ctx.setFontSize(unit * 30);
        ctx.setFillStyle("#fff");
        ctx.fillText("我是主要标题", unit * 25, unit * 50);
        ctx.setFontSize(unit * 16);
        ctx.setFillStyle("#fff");
        ctx.fillText("我是副标题", unit * 25, unit * 80);
        ctx.setFontSize(unit * 14);

        //绘制圆形头像
        ctx.save();
        ctx.beginPath();
        ctx.arc(unit * 318, unit * 44, unit * 16, 0, unit * Math.PI * 2, false);
        ctx.clip();
        ctx.drawImage(userimg, unit * 300, unit * 24, unit * 36, unit * 36);
        ctx.restore();

        //设置用户名称,并且指定位置自适应居中
        var runer = '我叫MT';
        runer = runer.split('');
        runer = runer[0] + '***' + runer[runer.length - 1];
        var runner_center = unit * 320;//指定位置
        var font_half_len = (ctx.measureText(runer).width) / 2;
        var runner_wd = runner_center - font_half_len; //居中设置
        ctx.fillText(runer, runner_wd, unit * 80);

        //设置表格--标题
        ctx.setFontSize(unit * 14)
        ctx.setFillStyle("#63C0AC")
        ctx.fillText("标题", unit * 30, unit * 130)
        ctx.fillText("标题", unit * 100, unit * 130)
        ctx.fillText("标题", unit * 180, unit * 130)
        ctx.fillText("标题", unit * 284, unit * 130)

        //设置表格--列表
        var space_list = custem_space.space_list;
        var aver_space = '底部文案';
        var space_len = space_list.length;
        ctx.setFontSize(unit * 14)
        var list_bgtop_size = unit * 144;
        for (let i = 0; i < space_len; i++) {
          if (i % 2 != 0) {
            ctx.fillStyle = "#f7fcfb";
            ctx.fillRect(0, list_bgtop_size, res.screenWidth, unit * 30);
          }
          list_bgtop_size = list_bgtop_size + unit * 30;
        }
        var list_top_size = unit * 164;
        for (let i = 0; i < space_len; i++) {
          let info = space_list[i];
          ctx.setFillStyle("#333")
          ctx.fillText(info['content'], unit * 30, list_top_size)
          ctx.fillText(info['content'], unit * 180, list_top_size)
          ctx.fillText(info['content'], unit * 284, list_top_size)
          ctx.setFillStyle("#63C0AC")
          ctx.fillText(info['content'], unit * 100, list_top_size)
          list_top_size = list_top_size + unit * 30;
        }
       
        //底部文案
        var footer_start = list_bgtop_size;
        ctx.drawImage(xcx_ewm, unit * 20,  footer_start + 20, unit * 70, unit * 70)
        ctx.setFontSize(unit * 14)
        ctx.setFillStyle("#999")
        ctx.fillText("微信扫一扫", unit * 96,  footer_start + unit * 45)
        ctx.fillText("看看我是谁", unit * 96, footer_start + unit * 70)
        ctx.setFontSize(unit * 22)
        ctx.setFillStyle("#63C0AC")
        ctx.fillText(aver_space, unit * 284,footer_start + unit * 45)
        
        //重置画布高度
        var canvas_totle_h = footer_start + 110;
        custem_space.canvas_h = canvas_totle_h+"px";
        that.setData({
          custem_space:custem_space
        });

       ctx.draw(false, function () {
       //一定要1秒钟之后,在调用canvasToTempFilePath()
        setTimeout(function () {
	        wx.canvasToTempFilePath({
	          x: 0,
	          y: 0,
	          width:  canvas_w,
	          height: canvas_totle_h,
	          //设置导出图片大小
	          destWidth: canvas_w * 2,
	          destHeight: canvas_totle_h * 2,
	          canvasId: 'space_img',
	          success: function (res) {
	            setTimeout(function () {
	              wx.saveImageToPhotosAlbum({
	                filePath: res.tempFilePath,
	                success: (res) => {
	                  wx.showToast({
	                    title: "保存相册成功"
	                  })
	                },
	                fail: (err) => {
	                  wx.showToast({
	                    title: "保存相册失败"
	                  })
	                }
	              })
	            },500)
	          },
	          fail: (err) => {
	           console.log('获取图片失败')
	          }
	        })
	   },1000)
    });
   }
})
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值