mini-programs-rc

Making github.com/fyuanz/mini… NPM www.npmjs.com/package/min…

Welcome to communicate

features

  • High-performance and loosely coupled rendering architecture
  • Super lightweight code volume
  • Support Canvas element management
  • Support for Canvas element event system
  • Complete group nesting system
  • Supports deformable clip clipping system
  • Built-in text, bitmaps, drawing objects and a variety of vector drawing objects
  • Built-in picture loader

Quick access to

  • One minute for introductory use
  • See examples of projects or secondary development
  • Built-in objects
    • Group
      • Group method
        • add
        • remove
        • empty
        • replace
    • Stage
      • Stage method
        • update
        • setHitCanvas
        • getTextWidth
        • loadImage
    • Bitmap
    • Text
      • Text method
        • getWidth
    • Graphics
    • Shape
      • Rect
      • Circle
      • Ellipse
  • attribute
    • Transform
    • Alpha
    • CompositeOperation
    • Shadow
    • Stage
  • methods
    • destroy
  • The event
  • tailoring
  • Custom object
    • The custom Shape
    • Custom Element
  • Picture loader
  • Matters needing attention
  • License

One minute for introductory use

Download the project locally, download the dependencies through NPM, and then use the command NPM run build to build

Copy mian.js from dist directory to wechat applet project.

Use in page or Component

Declare the canvas in WXML and declare the canvas for click event judgment

Applets do not support virtual Canvas. Click events are judged by hit-Canvas rendering

<view class="container">
  <view class="container">
    <canvas
      bindtouchend="touchend"
      bindtouchmove="touchmove"
      bindtouchstart="touchstart"
      class="canvas"
      id="canvas"
      style="width:{{width}}px; height:{{height}}px"
      type="2d"
    ></canvas>
    <! -- Hide hit-canvas -->
    <canvas
      class="hit-canvas"
      id="hitCanvas"
      style="width:{{width}}px; height:{{height}}px"
      type="2d"
    ></canvas>
  </view>
</view>
Copy the code

Hide class=”hit-canvas” in WXSS

.hit-canvas {
  position: fixed;
  top: -999rpx;
  left: -999rpx;
}
Copy the code

Introduces and initializes projects in JS

import mprc from 'main.js';
const { Stage, Group, Graphics, Rect, Circle } = mprc;

Page({
  data: {
    width: 375.height: 300
  },

  onReady: async function () {
    const canvas = await this.getContainer('#canvas');
    const stage = new Stage(canvas, this.data.width, this.data.height);
    const hitCanvas = await this.getContainer('#hitCanvas');
    stage.setHitCanvas(hitCanvas);
  },

  // Event listener
  touchstart: function (event) {
    stage.touchStartHandler(event);
  },

  touchmove: function (event) {
    stage.touchMoveHandler(event);
  },

  touchend: function (event) {
    stage.touchEndHandler(event);
  },

  // Get the canvas method
  getContainer(id) {
    return new Promise((resolve, reject) = > {
      const query = wx.createSelectorQuery();
      query
        .select(id)
        .fields({ node: true.size: true })
        .exec(res= > {
          const canvas = res[0].node; resolve(canvas); }); }); }});Copy the code

After initializing the project, draw the content

// Set the transparency of the container
const group = new Group();
group.x = 50;
group.y = 50;
group.alpha = 0.8;

// Draw the rectangle shape and set the transparency. The transparency will be displayed in combination with the transparency of the collection
const rect = new Rect(100.200, {
  fillStyle: '# 000000'
});
rect.alpha = 0.2;
rect.hitBox = [0.0.100.200];

// Set clipping, clipping will be performed
const clipPath = new Graphics();
clipPath.arc(50.50.50.0.Math.PI * 2);
rect.clip(clipPath);

// Draw a circular shape and set the drag event
const circle = new Circle(50, {
  fillStyle: 'red'
});
circle.on('drag'.function (event) {
  circle.x += event.dx;
  circle.y += event.dy;
  stage.update();
});

// Put the rectangle and circle shapes into the collection
group.add(circle);
group.add(rect);

// Put the collection into the root container
stage.add(group);

// Update render
stage.update();
Copy the code

See examples of projects or secondary development

npm run watch

Use the mini program editor of wechat to import the appellate P files.

Built-in objects

Group

For grouping, groups can also be nested groups. Attributes of the parent container are superimposed on child attributes, for example:

  • The x of the group is 100, the x of the bitmap in the group is 200, and the x of the final bitmap rendered to the stage is 300
  • The alpha of the group is 0.7, the alpha of the bitmap in the group is 0.6, and the alpha of the final bitmap rendered to the stage is 0.42
const group = new Group();
const rect = new Rect(100.100, {
  fillStyle: 'black'
});
group.add(rect);
stage.add(group);
stage.update();
Copy the code

Groups have the common add and remove methods for adding and removing elements. The ones that are added first will be drawn first, and all the ones that are added later will be overlaid.

Group method

add

Add the object

group.add(child);
Copy the code
remove

Remove the object

group.remove(child);
Copy the code
empty

Clear empty child objects

group.empty();
Copy the code
replace

Use an object instead of a child object

group.replace(current, pre);
Copy the code

Stage

The largest top-level container inherits from the Group, so it has all the methods that the Group has.

Stage method

update

Any element added to the Stage is not visible and requires the update method.

Perform stage.update() to update the render for any changes to element attributes.

stage.update();
Copy the code
setHitCanvas

Set up to simulate the virtual Canvas and accept a canvas object as a parameter to calculate the pixel-level touch event target.

Copy the code
getTextWidth

Gets the width of the text to be rendered using two parameters: text: String, the text to be drawn, and font: String, the style of the text to be set.

loadImage

The Stage built-in image loader accepts a url: string and returns a Promise object.

The result of the Promise execution is the Image object, which is used for bitmap drawing.

const stage = new Stage(canvas, 200.200);
const imgObj2 = await stage.loadImage('.. /logo.png');

const bitmap = new Bitmap(imgObj2);
stage.add(bitmap);
stage.updata();
Copy the code

Bitmap

Bitmap takes one parameter, an instance of the Image object, cannot use a URL or local path, Bitmap is synchronous, no callback method.

const bitmap = new Bitmap(img);
stage.add(bitmap);
stage.update()
Copy the code

You can set the clipped image display area, and other Transform properties:

const bitmap = new Bitmap(img);
bitmap.x=50;
stage.add(bitmap);

const clipPath = new Graphics();
clipPath.rect(0.0.100.200);
clipPath.x = 0;
clipPath.y = 50;
bitmap.clip(clipPath);
stage.add(bitmap);
stage.update()
Copy the code

Text

Text object

const text = new Text(item.key, {
  font: `normal normal 20px Arial`.color: '# 000000'.baseline: 'bottom'
});
Copy the code

Text method

getWidth

Get text width

textObj.getWidth();
Copy the code

Graphics

A drawing object used to draw graphics using the basic concatenation Canvas instruction.

const graphics = new Graphics();
graphics
  .beginPath()
  .arc(0.0.10.0.Math.PI * 2)
  .closePath()
  .fillStyle('#f4862c')
  .fill()
  .strokeStyle('black')
  .stroke();

graphics.x = 100;
graphics.y = 200;

stage.add(graphics);
Copy the code

Note, in particular, that if you are performing graphics concatenation drawing operations in a loop, be sure to include the clear() method otherwise the path will overload your browser:

setInterval(function () {
  graphics
    .clear()
    .beginPath()
    .arc(0.0.10.0.Math.PI * 2)
    .stroke();
}, 16);
Copy the code

Shape

Rect

const rect = new Rect(200.100, {
  fillStyle: 'black'
});
Copy the code

Circle

const circle = new Circle(10);
Copy the code

Ellipse

const ellipse = new Ellipse(120.20);
Copy the code

attribute

Transform

The property name describe
x The horizontal offset
y The vertical migration
scaleX The level of zoom
scaleY Vertical scaling
scale Set or read scaleX and scaleY simultaneously
rotation rotating
skewX Skew X
skewY Skewed Y
regX Base point of rotation X
regY Rotation base Y

Alpha

The property name describe
alpha Transparency of elements

If both father and son set alpha they multiply.

compositeOperation

The property name describe
compositeOperation Overlay mode in which the source image is drawn onto the target image

Note that if a compositeOperation is not defined, it will look up and find the parent container with the latest compositeOperation defined as its compositeOperation.

Shadow

The property name describe
shadow shadow

Usage:

obj.shadow = {
  color: '#42B035'.offsetX: -5.offsetY: 5.blur: 10
};
Copy the code

Stage

Name Describe
stage Or their stage

Usage:

obj.stage;
Copy the code

methods

destroy

Destroy themselves

obj.destroy();
Copy the code

Note: Group destruction destroys all objects in the Group

The event

The event name describe
tap Touch your finger and leave immediately
touchstart Finger touch begins
touchmove Fingers move after touch
touchend End of finger touch action
drag Drag and drop

Events fire with pixel accuracy. If you want to use the rectangle area of an element as the click area, you need to set the hitBox of the setting element.

tailoring

const stage = new Stage(600.400.'body');
const bitmap = new Bitmap(imgObj2);

const clipPath = new Graphics();
clipPath.arc(40.40.25.0.Math.PI * 2);
bitmap.clip(clipPath);

stage.add(bitmap);
Copy the code

The same effect can be achieved with the following code:

const stage = new Stage(600.400.'body');
const bitmap = new Bitmap(imgObj2);

const clipPath = new Graphics();
clipPath.x = 40;
clipPath.y = 40;
clipPath.arc(0.0.25.0.Math.PI * 2);
bitmap.clip(clipPath);

stage.add(bitmap);
Copy the code

Cutting area also support all the transform properties (x, y, scaleX, scaleY, rotation, skewX, skewY, regX, regY).

Custom object

The custom Shape

Custom Shape inherits from Shape:

class Sector extends Shape {
  constructor(r, from, to, option) {
    super(a);this.option = option || {};
    this.r = r;
    this.from = from;
    this.to = to;
  }

  draw() {
    this.beginPath()
      .moveTo(0.0)
      .arc(0.0.this.r, this.from, this.to)
      .closePath()
      .fillStyle(this.option.fillStyle)
      .fill()
      .strokeStyle(this.option.strokeStyle)
      .lineWidth(this.option.lineWidth) .stroke(); }}Copy the code

The use of Shape:

const sector = new Sector(10.0.Math.PI/6, {
  fillStyle: 'red'
  lineWidth: 2
})
stage.add(sector)
stage.update()
Copy the code

Custom Element

Custom Element inherited from Group:

class Button extends Group {
  constructor (option) {
    super(a)this.width = option.width
    this.roundedRect = new  RoundedRect(option.width, option.height, option.r)
    this.text = new Text(option.text, {
      font: option.font,
      color: option.color
    })

    this.text.x = option.width / 2 - this.text.getWidth() / 2 * this.text.scaleX
    this.text.y = option.height / 2 - 10 + 5 * this.text.scaleY
    this.add(this.roundedRect, this.text)
  }
}

export default Button
Copy the code

Use:

const button = new Button({
  width: 100.height: 40.text: 'Click Me! '
});
Copy the code

In general, it is recommended to use inheritance from Group for more complex assemblages, which is convenient for scaling and managing its own internal components.

Picture loader

The image loader returns a Promise

const { loadImage } = mprc;

The canvas argument is the canvas 2D object instance obtained
const imgObj = await loadImage('.. /logo.png', canvas);

// stage's image loading method
const stage = new Stage(canvas, 200.200);
const imgObj2 = await stage.loadImage('.. /logo.png');

const bitmap = new bitMap(imgObj2);
stage.add(bitmap);
stage.updata();
Copy the code

Matters needing attention

The project references applets, mini-games, and the Web’s general-purpose Canvas rendering engines Cax and Spritejs. Thanks to Cax and spritejs developers.

  • Cax is a cross-platform project, but only supports the old version of small program Canvas (wechat has given up maintenance). This project only supports wechat small program Canvas2D (base library 2.9.0 or above)

  • Some of the methods and attributes of the project are similar to Cax, but there are some differences, so be careful when using them

  • The initialization parameter of this project is canvas object instead of ID, so it should be initialized after getting canvas object, please see the sample code for details

  • Currently unsupported functions

    • Fixed is not supported
    • Frame animation is not supported
    • SVG Path rendering is not supported
    • Filters are not supported

Project light weight, simple to use, can be used for text, pictures, graphics, etc. Suitable for poster, puzzle, chart display and other project development.

Good support for gesture-related events, built-in drag and drop function, support rectangular boundary and pixel level boundary selection methods.

The project initializes the canvas by setting the width and height of the display and adjusting the pixel density through zooming to display high definition.

For more complex projects, it is recommended to develop components through classes, where each component is a class that contains its own layout and update methods. This allows you to develop highly reusable components that are easy to maintain later.

To do

  • The frame of animation