Some time ago, I had the need to dynamically generate pictures in the small program and then share them, which was a very common scene. Therefore, I selected a small tool CanvasPainter. Js, which includes the basic requirements of canvas drawing in the small program:

  • Drawing with configuration form (support single and multiple lines of text, rectangle, circle, picture and round picture type), and support for subsequent preview and save as pictures, and all in Promise format.
  • Canvas size is 750px of the general design draft (optional), and it can be scaled in equal ratio under different screen models.
  • Image pre-download is supported for image generation, and the TMP path of image download is cached in a small program cycle.

The demo address

usage

It is also very simple to use ~ no need to touch wX. Various APIS, direct configuration initialization + call corresponding methods can be, one-stop service delicious ~

import CanvasPainter from './CanvasPainter';

const config = [
{type:'rect, width: 640, height: 560, x: 0, y: 0, color: '#fff'},
{type: 'text', text: 'Test text', color: '#1499f8',size: 50, x: 30,y: 100}] // Initialize const Painter = new canvasId ({canvasId: 'canvasId', context: }); painter.loadImgInAdvance(); // Pre-download images to local; If not active call, draw will be downloaded. // Update the path painter. ResetConfig (newConfig); Then (() => {console.log())'Drawing done');   
}).catch(e => {
    console.log('Failed to generate image', e); }); / / the preview painter. Preview (); // Save painter. Save (). Then () => {console.log()'Save done');   
}).catch(e => {
    console.log('Save failed', e);
});
Copy the code

The key points encountered during development are as follows:

  • How do I scale

    Since the length unit of canvas drawing is px, it can be solved by using canvas.scale() of the applet.

    const scale = wx.getSystemInfoSync().windowWidth / 750; this.ctx.scale(scale, scale); // This lets you scale the UI at 750pxCopy the code
  • Draw images for pre-download and cache

    Before calling ctx.drawImage(), the image must be downloaded to the local temporary path first. This step takes a long time. Therefore, you are advised to perform this step first. Temporary paths are valid for a small program cycle, so it is perfectly possible to cache local temporary paths. In this way, when canvas is repeatedly generated, only dynamic pictures will be downloaded, and fixed picture paths will be reused to avoid repeated downloading ~

    In addition, the image domain name should be configured in the background of the small program. In order to avoid accidents, the image URL should be verified before downloading the image. If the verification fails, the download will be skipped directly or the bottom pocket map will be used instead.

  • Download the image locally

    Before saving the image, you need to call wx.getSetting() to get whether the user has permission to download the image locally or to invoke the request permission popup. If the permission is denied, it is better to give a toast prompt and reset the download button to open-type=”openSetting”. When the user clicks again, it leads to the authorization page.

In addition, there are two points not warm tips when using:

  • The Canvas component has explicit and implicit control

    It is not recommended to use WX :if to control explicit implicit of canvas component, because after mounting canvas component to page, it will take about 200ms to draw() successfully. It is recommended to use display: None /block to control the image.

  • Pull out components based on the business

    It is suggested to further separate the function of generating shared images from components based on the current business, including embedding the canvas preview image and saving the canvas as image button (compatible with unauthorized downloading of images to the authorization page). Can also be more flexible to control the drawing and update the drawing time.

With these two points in mind, you can pull out a dynamic graph in minutes

Attached: complete API

Initialize the

new CanvasPainter(options)

options

  • CanvsId: canvas – id.

  • Context: Canvas uses the context, passing this when used within the component.

  • Config: Array []. Plot paths. The supported types are as follows:

    • The rect rectangle

      Complete configuration: {type: 'rect',
      	width: 640,
      	height: 560,
      	x:0,
      	y:0,
      	color: '#fff', // Fill is the fill color, Storke is the handwriting color stroke(optional):true, // indicates whether the pattern is fill or stroke. The defaultfalse, which is the fill state. Round (optional) :true// indicates whether it is round. The defaultfalse. }Copy the code
    • The text text

      Complete configuration: {type: 'text',
      	x:0,
      	y:30,
      	color: '#fff'// font:'xx', // font size: 20, // font align:'center'// align. Left by default. Decoration (optional) :'line-through', // Only dash mode for now hahaha}Copy the code
    • Multiline_text Multiline text

      Complete configuration: {type: 'multiline_text', line_limit: 30, // line height: 20, // line height... // the rest is the same as text}Copy the code
    • Image picture

      Complete configuration: {type: 'image',
      	url: ' '// image path x:' ', y: ' ', width: ' ', height:' 'Round (optional):true// Circle. The defaultfalse. }Copy the code
  • SaleBase (optional): Based on the design size, default 750.

Pre-download images:

CanvasPainter. LoadImgInAdvance (). Can be called immediately after instantiation of CanvasPainter.

Drawing:

canvasPainter.draw()

Preview large image:

canvasPainter.preview()

Save as a picture:

canvasPainter.save()

To change the config:

canvasPainter.resetConfig(newConfig)