Small program sharing module super detailed (recommended)

Lead: In the development of small program projects, sharing ability is almost necessary for each project, but the native share capacity is limited, not flexible enough, today we will come together, how to on the existing basis Enhance the ability of small program sharing to make information transfer more intuitive and flexible.

Sample Project Address: https://github.com/ycvcb123/share-system

small program sharing basic API introduction

WeChat sharing The API only provides the ability to share to WeChat friends, did not provide the ability to share a circle of friends, this is a scorpion! ! !

Some consultations collected online, there are two main reasons:

  1. Due to the flood, the public is flooded, the quality of the circle of friends There have been declined, if the applet is open to sharing a circle of friends, it may further affect the entire WeChat ecology, causing problems such as degradation, user loss.
  2. WeChat does not let the applet forward in the circle of friends, more “advertising” positions of the protection of friends, can not let this “fat” become public welfare facilities.

In fact, some children’s shoes should pay attention to the advertisements of some small procedures in a circle, but this ability has not been completely released, and will not let go of it in the future. The development of wisdom has long thought that the part of this paper will be said in this article by generating posters with small-range codes (sprinkle !!!).

OnshareAppMessage – Forward

Usage:

Page ({OnshareAppMessage: Function () {return {title: ‘xxxxx’, / / Custom Forward Title PATH: ‘/ Page / User? Id = 123’, // Share page pathimageUrl: ‘/common/images/xxx.png’ // share image aspect ratio 5: 4}}}) // If only written in the form, title default is a small program name, path is the path of the current page (with no parameters ), imageUrl current page screenshot page ({onShareAppMessage: function () {}})
   
trigger method (must be first written in the
page

the above-described method):

click capsule applet menu will pop up from the bottom of the forward option.
  1. Component open-type = "share" i.e.,
  2. After triggering effect is as follows:

小程序分享模块超级详解(推荐) To observe the above results, it is easy to see,

title

information is to share out limited, then we can do to share the picture of the article, let it take out more information about it? Here we enter the second part of the dynamic drawing on canvas share pictures

Based on canvas dynamic rendering share pictures

because a lot of information about each page is through the interface returns the user input or generated, is constantly changing, designer painted still pictures is certainly not sufficient to show that information, then we would have to, is there a way, is the

still pictures

and dynamic information drawn together after generating a new picture ? the answer is yes! ! ! to draw pictures and text together? We will think of the magical

canvas

, according to a small program canvas related to API drawn as follows:

// Create canvas (component must bind this, remember !!!) var ctx = wx.createCanvasContext ( ‘myCanvas’, this); // draw a picture on canvas ctx.drawImage (path, 0, 0, width, height); // draw the canvas on the text ctx.setFillStyle ( ‘# fff’); ctx.setFontSize (32); ctx.fillText (startTime, 24, 54); / / other information drawn // … ctx.draw ();
   
above has passed
canvas

to draw pictures and text together, how that this turn into a picture canvas for developers to use it? powerful little program provides us with a method native: wx.canvasToTempFilePath

// draw in the above code () callback used wx .canvasToTempFilePathvar that = this; ctx.draw (true, () => {setTimeout (() => {wx.canvasToTempFilePath ({canvasId: ‘myCanvas’, success: (res) => {that.setData ({// res.tempFilePath-generated image temporary path picUrl: res.tempFilePath});}}, that); // use here in the assembly must remember to bind this, remember! ! ! }, 300); // Add 300 milliseconds here to solve rendering problems during the drawing of small programs});
   
transmitting picture paths to

Tags to get the following results.

   Similarly: Put  Picurl 
Assignment to onshareAppMessage

Imageurl 小程序分享模块超级详解(推荐), shared outgoing pictures with dynamic information!

Different source pictures (local pictures, web pictures, base64 pictures) In the above example, the local image is drawn directly CTX .drawImage (Path, 0, 0, Width, Height) ,

Path

can be directly incoming picture path. However, if it is network picture or

DrawImage

is unable to draw directly, the following describes how both cases are compatible. . // converts the network picture to the local path handlenetimg: function (imagepath) {var there; return new promise Resolve, reject) => {wx.getimageInfo ({src: imagepath, success: function (res) {RESOlve (res);}});});} HandlenetImg (‘network image address’) .then ((res) => {console.log (res.path); // Output converted local image path CTX. DrawImage (res. path, 0, 0, width, height); // This picture can be drawn on the canvas}) Base64 picture

use

ctx.drawImage (base64Data, 0, 0, width, height)

in the applet developer tools can be drawn, however! ! ! This big scam! ! ! The real machine is invalid! ! ! (A minute …)
png picture
 png picture  PNG picture  PNG picture 
png picture

VAR HandleBase64IMG = function () {//wx.getfilesystemManager appler VAR fsm = wx.getFileSystemManager (); var file_name = 'base64src'; var base64src = function (base64data) { Return new promise => {// parsing Base64, extracting picture type: IMGTYPE, resolving content bodydata (remove Data: image / png; base64, later content) var [IMGTYPE, BODYDATA] = / Data: image \ / (\ w +); base64, (. *) /. EXEC (Base64Data) || []; if (! Igtype) {reject (New Error ('Error_Base64SRC_PARSE'));} / ** * wx.env.user_data_path * Local User Document * Local The user file is a new concept from the 1.7.0 version. Provides a user file directory to developers, developers have completely free read and write permissions for this directory. You can get the path to this directory via wx.env.user_data_path. * / var filepath = `$ {wx.env.user_data_path} / $ {file_name}. $ {ivtype}`; // Press the character encoded encoded eNCoding to the address file, write data DATA. FSM.Writefile ({FilePath, Data: BADYDATA, 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=> {// RESUST to the Base64 into the local path behind the picture, you can draw a success on the canvas That.ctx.drawImage (RES, LEFT, TOP, WIDTH, HEIGHT);});

Through some of the above, we already know how to use Canvas to draw pictures and text to generate a new picture, here producing a new problem : How do we save the generated pictures? ? ? We will then see how CANVAS generate pictures and how to save to the local

How to save to the photo album after canvas
   Want to save to the first step in the album first Of course, it is necessary to get the permissions of the album! ! ! 

// Access Album Authorization WX.GetSetting ({Success: (RES) => {// Check if there is access album Permissions, if not authorized by wx.authorize method (authorization only needs one, you can directly access the album) if (! Res.authsetting [‘scope.writePhotosalbum’]) {Console.log (‘Nothing to get Authorization ” ); wx.authorize ({Scope: ‘Scope.writePhotosalbum’, SUCCESS: (RES) => {// User Click to allow the logic to obtain the album information, as shown in the figure}})}}}) Get access to the album, save the picture to the photo album using wx.saveimagetophotosalbum wx.saveImagetopHotosalbum ({FilePath: That.data.sharePicPath, Success: (res) => {// Save Successful pop-up prompt, tell the user wx.showmodal ({Title: ‘Save to Mobile Photo Album “, Content:’ Send picture Go to a friend circle, invite friends to join ‘, confirmcolor:’ # 0bc183 ‘, confirmtext:’ know ‘, showcancel: false}}}

Generate small-range sequence code and verification small program codes

In the solution of the shared friends circle of the applet, there will be a small program code in the generated poster page, so that the user has Enter the entrance of the applet, how do this small program code generate?

小程序分享模块超级详解(推荐)

   

Note: ACCESS_TOKEN is required because the interface parameters of the small-range code are required, and the security starts. Usually call data to get base64 by the back to the front end.

We are returning to the topic:

The above three generated interfaces, you can use the situation as needed, because in my project, you need to generate different pages corresponding to Little routine code,

B

The type of interface is compared to my requirements, here is the use and self-test of
B 小程序分享模块超级详解(推荐) interface

B

Class Interface Addition, Export Official Description – Interface B: Suitable for the number of business scenes for the required number

, the maximum 32 visible characters, The page path band with parameters should be particularly paying! ! !

Page , SCENE

and other parameters are passed to the background, and the background call

B class Interface, return to the front-end a base64 picture data, we draw this data to the poster! ! !

Drawing method The above has been said to process for different source pictures (local pictures, web pictures, base64 pictures)

The picture of the small range code has been generated, then how do we want Measure? How can I know if the information carried in the small-range code is correct?
小程序分享模块超级详解(推荐)

The above method is relatively convenient during the development stage, but in the formal beta stage, This way is a bit awkward, some people think of real machine debugging? The official interface can only generate the two-dimensional code of the published applet that is, you scan the code and connect the production environment! ! ! There is no way to debug, what should I do? ? ?

Solution will take advantage of powerful applet developer tools! ! !

First saving the generated small range code to the computer, how to save to the local part after the above Canvas generates pictures.

Then select the two-dimensional code compilation mode by developer tool, and select a picture with a small-scale code in the folder! ! !

Note: Get
Scene 小程序分享模块超级详解(推荐)

decodeuricomponent

Page ({OnLoad (query) {// Scene Need to use Decodeuricomponent to get the Scene const scene = decodeuricomponent that is incorporated when generating QR code (QUER)y.scene)}})

disengagement configuration file to draw more flexible

We observed as a small poster procedure: 小程序分享模块超级详解(推荐)

in addition to the contents of the red box on the map will change other than writing, the overall structure is the most basic have been fixed since the poster content and services are strongly correlated, if I write logic components drawn in, it would mean a change in the business, I will change a component? So lost universal component is certainly not, how to do it? Here’s a better solution for the industry: applet poster saying that white is the

canvas
some shapes drawn on the canvas, pictures, text, lines, etc. make up, then we are these basic capabilities can not drawn into the packaging method, measure out a position on the size of each element design draft information posters, as a configuration file is passed to the rendering method, which ensures universal assembly, and drawing information pulled into a configuration file more convenient post-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 QR code, 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}]}

When several dynamic information is changed, The value of these changes can be passed.

小程序分享模块超级详解(推荐)

Import {setshareInfo} from ‘../../ Common / config / share-config’; Page ({onload: function () {this.setdata ({ ShareMessageInfotimeline: setshareinfo (‘March 7th at 16:30 PM “,’ Tencent Building ‘,’ Ping An International Center ‘,’ ‘)}); // …},});

   

This article splits the basic capabilities required for the small program sharing, and performs different combinations of the above capabilities, which should meet most of the sharing needs. .
 For example:   
Dynamic draws shared sharing to WeChat friends.
Build and save the small program poster.

The above is all the content of this article, I hope to help everyone, I hope everyone will support Tumi Clouds.

© Copyright Notice
THE END
Just support it if you like
like0
share
comment Grab the couch

Please log in to comment