//Page data initialization add parameter: issigncanvas show
//Convert the image to jpg through canvas, making the image generate a white background for easy viewing and Preview//List is the original image array list. index indicates the current image subscript. //imgList represents the list of pictures that have been converted through canvas trasformImgType(list,index,imgList){ this.setData({ isSignCanvasShow:true }); index=index?index:0; const that=this; let img=list[index].fileUrl; img=img.replace(/http/,'https'); tip.loading('Opening picture'); //Get picture information, wx.getImageInfo({ src: img, success (res) { //Draw in canvas const context = wx.createCanvasContext('picCanvas'); that.resetCanvas(context); context.drawImage(res.path,0, 0); context.draw(false,function(drawed){ // console.log(drawed); wx.canvasToTempFilePath({ x: 0, y: 0, width: 414, height: 300, destWidth: 414, destHeight:300, fileType: 'jpg', canvasId: 'picCanvas', success(imgRes) { tip.loaded(); imgList.push(imgRes.tempFilePath); if(index<list.length-1){ that.trasformImgType(list,index+1,imgList) return; } that.setData({ isSignCanvasShow:false }) wx.previewImage({ current: '', //Icon current subscript urls: imgList, // http link list of pictures to preview fail:function(res){ tip.alert('Pictures need to be refreshed after expiration'); }, }) }, fail() { that.setData({ isSignCanvasShow:false }) tip.loaded(); tip.alert('Pictures need to be refreshed after expiration'); } }) } ) } }) }, //Redraw Sketchpad resetCanvas(context){ context.rect(0, 0, this.data.screenWidth, this.data.screenHeight - 4); //Sketchpad size context.setFillStyle('#fff '); / / background fill context.fill() //Set fill context.draw() //Draw a picture },
wxml The following code needs to be added to the file:<view hidden="{{!isSignCanvasShow}}">
<canvas canvas-id="picCanvas" id='picCanvas' class="pic-canvas" ></canvas>
</view>
Method interpretation:
When previewing a picture through wx.previewImage, when the format is png and the preview background is black, the picture can not be viewed clearly. You can convert it to a white background through the following methods to facilitate viewing.
1. Use wx.getImageInfo to download the picture to the local area and get the picture information;
2. Draw the image into canvas and generate the temporary image address;
3. Fill in the address generated by canvas into imgList for caching;
4. After all the pictures are converted, call wx.previewImage to view the pictures.
5. When converting a picture, draw canvas again.