Introduction: In the small program project development, the ability to share is almost a necessary requirement for every project, but the original ability to share is relatively limited, not flexible, today we will study together, how to enhance the ability to share small program on the existing basis, make the information transfer more intuitive, flexible.

Example project address: github.com/ycvcb123/sh…

Contents of this article:

  • Applets share basic API introduction
  • Drawing and sharing pictures dynamically based on Canvas
  • Canvas’s processing of images from different sources (local images, Network images, Base64 images)
  • How to save images generated by Canvas locally
  • How to generate and verify the information contained in the applets
  • Extract configuration files to make drawing more flexible
  • conclusion

Applets share basic API introduction

Wechat share API only provides the ability to share to wechat friends, does not provide the ability to share the circle of friends, why!!

From some of the inquiries collected online, there are two main reasons:

  1. Due to the flood of wechat business, the flood of public number chicken soup, the quality of circle of friends has declined, if the small program to open the function of sharing circle of friends, may further affect the whole wechat ecology, resulting in a decrease in user activity, user loss and other problems.
  2. Wechat does not let the small program forward in the circle of friends, more is to protect the circle of friends “advertising space” position, can not let this “fat meat” into public facilities.

In fact, some children should notice that in wechat moments, the official has pushed some small program advertisements, but this ability has not been fully opened, will not be opened in the future, smart developers have already thought of generating posters with small program code as an alternative (scatter flowers!!). , which will be covered later in this article. Let’s get back to business.

OnShareAppMessage forward –

Usage:

Page({
    onShareAppMessage: function(){
         return {
            title: 'xxxxx'.// Customize the forwarding title
            path: '/page/user? id=123'.// Share the page path
            imageUrl: '/common/images/xxx.png' // Share image width ratio 5:4}}})// Title is the name of the applet by default, path is the path of the current page (no parameters), and imageUrl is the screenshot of the current page
Page({
    onShareAppMessage: function(){}})Copy the code

Trigger method (be sure to write the above method in page first) :

  1. Click on the capsule menu of the applet and the forward option pops up from the bottom.
  2. <button>Components in the open – type = “share” called<button open-type="share">Click and trigger.

The effect is as follows:

Observing the above results, it is not difficult to see that the information that title can share is very limited, so can we do some articles on the shared pictures, so that it can bring out more information? Let’s move on to the second part of drawing and sharing images based on canvas dynamics

Drawing and sharing pictures dynamically based on Canvas

Because each page a lot of information is returned or user input through interfaces, is changing, the designer painted static image is certainly not enough to go to show these information, so we’re going to want to, is there a way, is that you can draw static images and dynamic information together in generating a new image? The answer is yes!!

Put pictures and words together? We must think of the magic canvas, according to the applets canvas related API draw as follows:

// Create canvas (this must be bound to component, remember!!)
var ctx = wx.createCanvasContext('myCanvas'.this);
// Draw pictures on canvas
ctx.drawImage(path, 0.0, width, height);
// Draw text on canvas
ctx.setFillStyle('#fff');
ctx.setFontSize(32);
ctx.fillText(startTime, 24.54);
// Other information to draw
/ /...
ctx.draw();
Copy the code

The above picture and text have been drawn together through canvas, how to turn this canvas into a picture for developers to use?

A powerful applet gives us a native method: wx.canvastotempFilepath

// Use wx.canvastotempFilepath in the draw() callback of the code above
var that = this;
ctx.draw(true, () => {
    setTimeout((a)= > {
        wx.canvasToTempFilePath({
            canvasId: 'myCanvas'.success: (res) = > { 
                that.setData({
                    // res.tempFilepath Creates a temporary path to the image
                    picUrl: res.tempFilePath
                });
               
                
            }
        }, that); // When using this in a component, remember to bind this, remember!
    }, 300); // Add the 300 ms delay here to solve the rendering problem in the applet drawing process
});
Copy the code

Pass the image path to the tag to get the result below.

<image src="{{picUrl}}"/>
Copy the code

For the same reason: assign picUrl to imageUrl in onShareAppMessage and share the image with dynamic information!

Processing of images from different sources (local images, network images, Base64 images)

DrawImage (path, 0, 0, width, height) is used to draw the local image. However, if it is a network image or a Base64 image, drawImage cannot be drawn directly. Here is how to make compatible processing for the above two situations.

  1. Web source images
// Convert the network image to a local path
handleNetImg: function(imagePath) {
    var that = this;
    return new Promise((resolve, reject) = > {
        wx.getImageInfo({
            src: imagePath,
            success: function(res) { resolve(res); }}); }); } handleNetImg('Network Picture Address').then((res) = > {
    console.log(res.path); // Output the converted local image path
    ctx.drawImage(res.path, 0.0, width, height); // Now the image can be drawn on the canvas
})
Copy the code
  1. Base64 pictures

DrawImage (base64Data, 0, 0, width, height) is drawable on applets developer tools, however!! This big cheat paper!! The real plane is disabled!! (One minute of heartbreak…)

Along similar lines, we converted base64 images into local PNG images

var handleBase64Img = function() {
    / / wx. GetFileSystemManager small program file manager
    var fsm = wx.getFileSystemManager();
    var FILE_NAME = 'base64src';
    var base64src = function(base64data) {
        return new Promise((resolve, reject) = > {
            Imgtype, bodyData (data:image/ PNG; Base64, later)
            var [, imgType, bodyData] = /data:image\/(\w+); base64,(.*)/.exec(base64data) || [];
            if(! imgType) { reject(new Error('ERROR_BASE64SRC_PARSE'));
            }
            /** *wx.env.USER_DATA_PATH * Local user file * Local user file is a new concept from version 1.7.0. Provides a user file directory for developers, developers have full freedom to read and write to this directory. You can obtain the path of this directory by using wx.env.USER_DATA_PATH. * /
            var filePath = `${wx.env.USER_DATA_PATH}/${FILE_NAME}.${imgType}`;
            // Encoding writes data to address filepath.
            fsm.writeFile({
                filePath,
                data: bodyData,
                encoding: 'base64',
                success() {
                    resolve(filePath);
                },
                fail() {
                    reject(new Error('ERROR_BASE64SRC_WRITE')); }}); }); };return base64src;
}

var base64src = that.handleBase64Img();
var handleBase64src = base64src(base64data);
handleBase64src.then(res= > {
    //res is the local path after base64 is converted into an image, which can be successfully drawn on the canvas
    that.ctx.drawImage(res, left, top, width, height);
});
Copy the code

Through some of the above content, we have known how to use canvas to draw pictures and text together to generate a new picture, here comes a new problem: how to save the generated picture?? Let’s take a closer look at how to save images generated by canvas locally

How to save pictures generated by Canvas to album

The first step to save to the album is of course to get access to the album!!

// Access album authorization
wx.getSetting({
    success: (res) = > {
        // Check whether you have the permission to access the album. If not, authorize the album through the wx.authorize method.
        if(! res.authSetting['scope.writePhotosAlbum']) {
            console.log('No authorization is obtained');
            wx.authorize({
                scope: 'scope.writePhotosAlbum'.success: (res) = > {
                    // The user clicks allow to get album information and the logic enters here, as shown in the picture above}})}}});/ / obtain the access of the album, the use of wx. SaveImageToPhotosAlbum to save images into the photo album
wx.saveImageToPhotosAlbum({
    filePath: that.data.sharePicPath,
    success: (res) = > {
        // A message is displayed indicating that the save is successful
        wx.showModal({
            title: 'Saved to phone album'.content: 'Send pictures to moments and invite friends to join'.confirmColor: '#0bc183'.confirmText: 'Got it.'.showCancel: false})}})Copy the code

How to generate and verify the information contained in the applets

In the solution of small program sharing circle of friends, there is often a small program code in the generated poster page, so that the user has access to the small program, so how to generate this small program code?

Official documentation: Get small program code

Note: Since the interface argument to generate the applets requires an access_token, the base64 data is usually returned to the front-end through background calls for security purposes.

Let’s get back to the point:

The above three generation interface, we need to use according to the situation, because my project, often need to generate different pages corresponding to the small program code, CLASS B interface is more in line with my requirements, here is the focus on the use of class B interface and self-test

Interface B: applies to service scenarios where a large number of codes are required

Scene: up to 32 visible characters, especially if there is a page path with parameters.

After passing page,scene and other parameters to the background, the background calls class B interface and returns to the front end a Base64 picture data, we draw this data to the poster!!

Drawing method It has been mentioned above that Canvas handles images from different sources (local images, network images, base64 images)

Now that the picture of the applet code has been generated, how do we test ourselves? How do I know if the information contained in the applets is correct?

The official method:

The above method is more convenient in the development stage, but in the formal test stage, this way seems to be a little far-fetched, some people think of real machine debugging?

The official interface can only generate the QR code of published applets

That is to say, you scan the code connected to the production environment!! There is no way to debug, so what on earth to do?

The solution is to use a powerful small program developer tools!!

First, save the generated small program code to the computer. See how to save the local part of the picture generated by canvas above.

Then select the two-dimensional code compilation mode through the developer tool, select the picture with small program code in the folder!!

Note: getsceneValue todecodeURIComponent

Page({
  onLoad(query) {
    // scene Need to use decodeURIComponent to get the scene generated qr code
    const scene = decodeURIComponent(query.scene)
  }
})
Copy the code

Extract configuration files to make drawing more flexible

Let’s observe the following small program poster:

In addition to the content in the red box above, the overall structure is basically fixed, because the content of the poster is strongly related to the business. If I write the drawing logic into the component, won’t that change the business, and my component will have to change once? This is certainly not possible without the component’s generality, so what can be done? Here is a good solution for the industry:

Small program poster namely from the canvas to draw on the canvas of some shapes, images, text, lines, and so on, then we can draw the basic ability of encapsulation methods, through the design draft out information such as the position and size of each element in the paper, as a configuration file is passed to the draw method, so as to ensure universal components, Moreover, drawing information into a configuration file is more convenient for later maintenance.

share-config.js:

function setShareInfo(time, start, end, imageSrc) {
    return {
        width: 750.height: 1300.background: '#F2FCF8'.views: [{
                type: 'rect'.parent: true.radius: true.radiusVal: 16.left: 40.width: 670.height: 1140.shadow: true.background: '#cacacd'.shadowColor: 'rgba(0,0,0,.6)'.line: true
            },
            //....
            {
                type: 'text'.content: 'Long press or scan the QR code to view this line'.color: '#9B9BA1'.top: 1052.left: 224.fontSize: 28.font: 'PingFangSC-Medium'}, {type: 'image'.path: '/common/images/station-flag.png'.top: 746.left: 80.width: 32.height: 104}}}]export {
    setShareInfo
}
Copy the code

You simply pass in the values of the changes as several dynamic messages change.

import { setShareInfo } from '.. /.. /common/config/share-config';
page({
    onLoad: function() {
        this.setData({
            shareMessageInfoTimeline: setShareInfo('It leaves at 16:30 PM on March 7th'.'Tencent Tower'.'Safety International Centre'.' ')});/ /...}});Copy the code

Obtain the configuration information from shareMessageInfoTimeline

<view class="container">
    <mod-share-timeline timelineShow="{{timelineShow}}" picContent="{{shareMessageInfoTimeline}}" bindcloseTimelineShow="closeTimelineShow"/>
</view>
Copy the code

conclusion

In this paper, the basic ability of small program sharing is divided into details, the ability of different combinations, should be able to meet most of the sharing needs.

Such as:

  1. Dynamically draw shared pictures shared with wechat friends.
  2. Generate and save the applet poster.

Through this article, the following knowledge points can be mastered:

  • Applets share the base API
  • Drawing and sharing pictures dynamically based on Canvas
  • Canvas’s processing of images from different sources (local images, Network images, Base64 images)
  • How to save images generated by Canvas locally
  • How to generate and verify the information contained in the applets
  • Extract configuration files to make drawing more flexible

I wrote a sample demo on Github based on the above basic abilities for easy reference and practice:

Github.com/ycvcb123/sh…