This is the 4th day of my participation in the August More Text Challenge

Usage scenarios

The article details page in the mini program has a sharing function: users click the share button to generate a shared picture (including the cover image, introduction and the small program code with the article ID), which is convenient for users to save locally.

Problem specification

The small program code is obtained through the background interface in the following format: ‘data:image/ JPG; base64,/9j/4AAQSkZJRgAB… ‘(only the first part is taken)

After being drawn by Canvas, it is valid on wechat developer tool, but invalid on real phone.

The solution

The small program code through a small program in the API first FileSystemManager. WriteFile () interface written to a local and get a temporary URL.

The key code

Write the small program code locally

Export const writeFile = (base64Str =>{return new Promise((resolve,reject)=>{// Let base64Image = base64str.split (',')[1].replace(/[\r\n]/g, '); // File manager const FSM = wx.getFilesystemManager (); // file name const FILE_BASE_NAME = 'tmp_base64src'; // File suffix const format = 'PNG '; Const timestamp = (new Date()).gettime (); const timestamp = (new Date()).gettime (); // base to binary const buffer = wx.base64toarrayBuffer (base64Image), FilePath = '${wx.env.USER_DATA_PATH}/${timestamp}share.${format}'; WriteFile ({filePath, data: buffer, encoding: 'binary', success(res) {// wx.getimageinfo ({SRC: filePath, success: function(res) { let img = res.path; // Expose the temporary URL of the image that needs to be drawn. reject(); }, fail(e){console.log(' error reading image '); console.log(e); }, error(res) { console.log(res) } }) }, fail(e){ console.log(e); } }) }).catch((e) => { console.log(e); })});Copy the code

Call a method on the page

Import {writeFile} from '.. /.. /utils/wxFunc' getUseCode () {writeFile(codeUrl).then(img => {// // codeUrl = base64 console.log(' ' + img); / / img format: http://usr/1599468897794share.png this. CreateCanvas (img); }).catch(e => { console.log(e); })}Copy the code

As a final refinement, each call to write a file will cause more files to be written and an error will be reported when the total file size in the file manager exceeds the maximum limit. Solution: Delete the file before writing it.