canvas制作完美适配分享海报

基于mpvue实现的1080*1900小程序海报
html
 1 <canvas class="canvas" :style="'width:'+windowWidth+'px;height:'+windowWidth/(1080/1900)+'px;'" canvas-id="firstCanvas"></canvas> 
 
js
 1 const windowWidth = this.windowWidth
 2 const fit = 1080 / 1900 //dpr
 3 const widFit = windowWidth / 1080 //宽比 (像素375所以除2,下同理)
 4 const heiFit = windowWidth / fit // 750 / (1080 /1900)
 5 const ctx = wx.createCanvasContext('firstCanvas')
 6 ctx.save()
 7 ctx.drawImage(this.backgroundUrl, 0, 0, windowWidth, windowWidth/fit)
 8 
 9 ctx.save()
10 ctx.beginPath()
11 ctx.arc(206*widFit, 713/1900*heiFit, 53*widFit, 0, 2 * Math.PI)
12 ctx.clip()
13 ctx.drawImage(this.face, 153*widFit, 660/1900*heiFit, 106*widFit, 106*widFit)
14 ctx.restore()
15  
16 ctx.save()
17 ctx.beginPath()
18 ctx.arc(540*widFit, 1602/1900*heiFit, 105*widFit, 0, 2 * Math.PI)
19 ctx.clip()
20 ctx.drawImage(this.qrcode, 435*widFit, 1497/1900*heiFit, 210*widFit, 210*widFit)
21 ctx.restore()
22 
23 ctx.draw(false,function(){
24   wx.canvasToTempFilePath({
25     destWidth: 1080,
26     destHeight: 1900,
27     canvasId: 'firstCanvas',
28     quality: 1,
29     success(res) {
30       console.log(res)
31     },
32     complete(fin){
33       console.log('finish',fin)
34       if(fin.tempFilePath){
35         wx.saveImageToPhotosAlbum({
36           filePath: fin.tempFilePath,
37           success: (result)=>{
38             wx.showToast({
39               title: '保存图片成功',
40               icon: 'none'
41             })
42           }
43         })
44       }
45     }
46   })
47 })

 
核心主要是换算比例
 
posted @ 2018-12-28 15:21  小白是鱼骨头呀!  阅读(535)  评论(0编辑  收藏  举报