Wechat applet uses canvas to draw circular avatars in posters

Use canvas to achieve the following renderings

Insert image description here

  • Use the official canvas API of the WeChat applet. If you need to know more, you can check the reference document , and directly upload the code without repeating it here.

canvas.wxml

 <view>
    <canvas class="firstCanvas _6a4ef3a" style="width:{
   
   {windowWidth}}px;height:{
   
   {windowHeight}}px;" canvas-id="firstCanvas" bindlongtap="generate"/>
  </view>

canvas.js

let promiseAvatar=null;  //定义暂存头像的function
const ctx = wx.createCanvasContext('firstCanvas'); //定义画图常量
Page({

  /**
   * 页面的初始数据
   */
  data: {
  		windowHeight:0,
  		windowWidth:0
		rate:0  //适配参数
  },


methods:{

 	//获取设备参数
  	getWindowInfo() {
  	  	let {windowWidth,windowHeight} = wx.getSystemInfoSync();
    	let  rate = windowWidth / 750;  
        this.setData({windowWidth,windowHeight,rate})
    },

	getUserAvatar(){
		let userInfo=wx.getStorageSync('userInfo),
    	userAvatar=userInfo.avatarUrl,promiseAvatar;	
		return new Promise(function (resolve, reject) {
        	   wx.getImageInfo({
          	   src: userAvatar,
          	   success: function (res) {
            		resolve(res);
          	   },	
          	   fail: function (res) {
            		reject(res);
          	    }
        	});
	},
	
 	async  drawImage(){
 			let {rate} = this.data;
      		let res = await getUserAvatar();
			// 因为这个是其他的画报中截取的片段,所以这里要先保存一下
			// 大致的实现步骤rate
			//	绘制一个圆进行截切   ctx.clip() 
			// 最后填充图片
		
			ctx.save();  //保存原有的画图
    		ctx.beginPath()  //重新开始
    		ctx.arc(  //绘制圆心坐标为(350,132),半径为66的圆
          		Math.floor(375 * rate), 
          		Math.floor(132 * rate), 
          		Math.floor(66 * rate), 
          		0, 
         		 2 * Math.PI
       		 ); 
    		ctx.clip()  //裁剪
    		ctx.drawImage( //定位在圆圈范围内便会出现
          		res[0].path,  //图片暂存路径
          		Math.floor(310 * rate),
          		Math.floor(66 * rate),
          		Math.floor(132 * rate),
          		Math.floor(132 * rate)
       		 ); 
    		ctx.restore()
    		ctx.draw()
    }
  }
  onShow(){
  		this.getWindowInfo();
    	this.drawImage();
   }
})

What needs to be noted about pictures is that if it is a network resource, you need to download the picture to a temporary path before using it. Call the wx.downloadFile method, and then draw the picture path using the path returned by this method (the download domain name of the file needs to be in the background of WeChat Configure it)

Guess you like

Origin blog.csdn.net/qq_41194534/article/details/88122837