The default size of the picture shared with friends by the small program is 5:4. The size of the picture provided in the actual business may not be exactly this proportion. By default, wechat cuts the picture from the upper left corner, while the main information of the general picture is in the middle, so it is easy to lose the main information of the picture by default

We use Canvas to crop the picture manually and generate the shared picture

// index. WXML uses canvas2D interface, Make clipping support GIF <canvas ID ="j-clip" type="2d" style="{{clipStyle}} {{customStyle}}"></canvas> // index.js import canvasClip from './lib/clip.js' Component({ properties: { customStyle: { type: String }, src: { type: String } }, data: { clipStyle: 'width: 500rpx; height: 400rpx; position: absolute; z-index: 999; top: 9999rpx; left: 9999rpx; Wx.showloading ({title: '', mask: {title: '', lifeTimes: {ready() {wx.showloading ({title: '', mask: Observers: true})}}, observers: { src(val) { val && canvasClip('#j-clip', val, this).then(path => { this.triggerEvent('done', path) setTimeout(function() { wx.hideLoading() }) }).catch(err => { this.triggerEvent('fail', err) wx.hideLoading() }) } } }) // ./lib/clip.js const canvasClip = (canvasId, url, self, cw = 500, ch = 400, ratio = 5 / 4) => { return new Promise((resolve, reject) => { wx.createSelectorQuery().in(self) .select(canvasId) .fields({ node: true }) .exec(res => { const canvas = res[0].node canvas.width = cw canvas.height = ch const ctx = canvas.getContext('2d') const img = canvas.createImage() img.onload = () => { let x = 0 let y = 0 let imgWidth = ImgHeight = img.height // imgsimgWidth let sImgHeight if ((imgWidth/imgHeight) > ratio) {img.width // imgWidth sImgHeight = ch sImgWidth = (sImgHeight * imgWidth) / imgHeight x = -(sImgWidth - cw) / 2 } else { sImgWidth = cw sImgHeight = (sImgWidth * imgHeight) / imgWidth y = -(sImgHeight - ch) / 2 } ctx.drawImage(img, x, y, sImgWidth, sImgHeight) wx.canvasToTempFilePath({ canvasId: canvasId, canvas: canvas, success: res => { const path = res.tempFilePath resolve(path) console.log('************* path', path) }, fail: (err) => {reject(' reject: Store canvas to temporary path ', err)}})} img.src = URL})})} export default canvasClipCopy the code