Brief introduction:

In business, we often meet the needs of various synthetic pictures, such as sticker synthesis, text synthesis, adding watermarks, etc., because these businesses often need to calculate various parameters such as position and state, which is not so convenient to write. This plug-in is to solve this part of the difficulty, encapsulate the underlying API and various calculations, provide a simpler API to use, reduce the repetitive work on the project, improve efficiency;

Update:

  • 1.3.4 (6.22)

    • Modified text drawing mechanism, added text rotation parameter,option.pos.rotate;
  • 1.3.2 (4.28)

    • addfunctionwidthParameters of the neworiginIs drawn according to the size of the original picture;
    • Text rendering added fault tolerance: whenoptions.width < fontSize, the pressfontSizeDraw to avoid the problem of swapping blank lines;
    • Fix the problem that initialization does not send parameters wrong;
  • 1.3.1 (4.28)

    • repairtextThe problem of multiple calls affecting each other;
  • 1.3.0 (2.22)

    • Modify the parameter format of the new instance, which is relatively unified and easy to expand;
    • Optimized storage management classification, added on instancefndataProperties;
    • The new Apimc.rect / mc.circle, used to draw rectangles and circles;
    • correctmc.textMethods To locate the inaccurate problem, and add the function of stroke text, gradient text, text shadow;
    • Added error callbacks that are triggered when images fail to loaddrawIn the incomingerrorThe callback.
    • Optimize documentation and code;
  • 1.2.9 (12.20)

    • The new Apimc.clear: Empty the canvas;
  • 1.2.8 (10.27)

    • repairbackgroundAPI interfaceleft/topParameter vertical center problem, in addition to new supportleft:'center', unified API;
  • 1.2.6 (9.27)

    • backgroundAPI interfaceleft/topParameters of the new0%,50%100%;
  • 1.2.5 (9.27)

    • Fix documentation errors;
  • 1.2.3 (9.26)

    • Increase the materialcanvasSize limit, ios8 is 2096, other limits are 4096;
  • 1.2.2 (9.25)

    • Add parameter round down;
  • 1.2.1 (9.7)

    • Modify theaddIn the functioncropClipping feature BUG;
  • 1.2.0 (8.28)

    • Modify themc.draw()Add configurable export image format and image quality, compatible with the old versionapi;
    • Add some error reminders that may cause errors to facilitate the business side to locate problems;
  • 1.1.8 (8.13)

    • Update documents;
  • 1.1.7 (8.12)

    • increasemc.background(bg)Error reminder when the interface is called for the first time, modify the content of the exception prompt;
  • 1.1.6 (8.11)

    • Fixed the problem of clipping canvas magnification error in vertical footage.
  • 1.1.5 (8.10)

    • increaseadd/background/watermarkThe incomingimageCan I do forcanvas;
  • 1.1.4 (8.9)

    • Add English documents;
    • Added the default background color that can be configured during initialization.
  • 1.1.3 (8.3)

    • Modify a warning syntax error;
    • Added a small canvas magnification mechanism for painting materials, which is used to solve the cropping caused by rotation.
    • Add the clearing mechanism after drawing a small canvas to avoid occupying too much memory due to too large material;
  • 1.0.9 (7.27)

    • Get picture width byimg.widthModified toimg.naturalWidthTo avoid direct incomingDOMNode to get the width and heightcssInfluence;
    • Add background image error alert;
  • 1.0.8 (7.27)

    • Adjust the constructor structure usingprototypeThe prototype chain is shaped to be compatible with the beltnewHow to call;
    • Adjust and improve documents;
    • Delete incorrect package dependencies and adjust package names;
  • 1.0.2 (7.26)

    • Revision and improvement of documents
    • BigStyle –> largeStyle;

Simple example (see API for details) :

Since the composition of images is asynchronous and strictly sequential, the form used is designed in a chain way, which is more semantic and logical;

First, a series of stories are prepared, and the stories to be drawn are added to the queue. Finally, draw and export the stories by calling Draw ().

// Create canvas, initialize canvas; let mc = new MC({ width: 1000, height: 1000, backgroundColor: 'black', }); // background: Prepare the background; Background ('imageUrl',{left:0, top:0, color:'#000000', type:'origin',}) // add .add('images/nose.png',{width:183, pos:{x:250, y:369, scale:0.84, rotate:1,},}).add('images/nose.png',{width:183, pos:{x:250, y:369, scale:0.84, rotate:1,},}) >< br><s> </s>,{width:'300px', align:'center', pos:{x:0, y:0,},}); .watermark(img,{width:'40%', pos:'rightBottom',}) // draw the final draw function, used for the final draw; .draw( b64 =>{ console.log(b64); });Copy the code

API:

Create instance:

new MCanvas(options) || MCanvas(options):

Create Canvas, initialize Canvas;

params:

  • {Object} options
    • {Number} width: optional canvas width;
    • {Number} height: canvas height, optional;
    • {Color} backgroundColor: optional canvas backgroundColor;

Usage:

	MCanvas({
		width : 500,
		height: 500,
		backgroundColor: '#fff',
	})Copy the code

Methods:

1.mc.background(image,options):

Draw the base of the canvas;

Options: Mandatory for the first time, optional later;

The parameters are stored as default values each time the background is drawn, so the background initialization can be restored by calling this function without passing a value.

Usage:

/ / image: the background image, type: url/HTMLImageElement HTMLCanvasElement MC. Background (image, {/ / drawing modes: Origin/crop/contain // origin: the original image mode, the size of the canvas is the same as the background image, ignore the initial width of the incoming canvas; Ignore left/top; // crop: crop mode, background image adaptively spread all over the canvas, cut the excess parts; The clipping part can be controlled by the left/ TOP value; // contain :contain; background-size:contain; The position can be controlled by the left/top value; Type :'origin', // The distance between the background image and the top left corner of the canvas, // 100 / '100%'/'100px' // 0% : left clipping; 50% : represents the center cut; Left :'50%', top:0, // only include type:contain; color:'#000000', })Copy the code

2,add(image,options)/add([{image:'',options:{}},{image:'',options:{}}]):

Generic add layer function, which can be used in the above two calls to add multiple or single images;

params:

/ / material picture, type: url/HTMLImageElement HTMLCanvasElement image: "', / / configuration parameters: options: {/ / the width of the material value, relative to the canvas. // example: width: 100 / '100%' / '100px'; Width :'100%', // Clipping coefficient relative to the material image; // crop params; Crop :{// The origin is the upper left point relative to the material graph; X: 0, y: 0, / / width is high, the need to cut example: / '100%' 100 / '100 px; // There is an internal maximum judgment; }, // position coefficient, relative to canvas; Pos :{// Coordinates relative to the canvas, the origin is the upper left point; Example: // x: 250 / '250px'/'100%'/'left:250'/'center', x:0, y:0, // Scale :1, // Material rotation Angle; rotate:0, }, }Copy the code

3,watermark(image,options):

Add watermark function, based on add() encapsulation, more portable and convenient to use; prepare the watermark;

params:

/ / material picture, type: url/HTMLImageElement HTMLCanvasElement image: "', / / configuration parameters: options: {/ / watermark size, in order to adaptive according to image, only support in the form of percentage; // The width is the width of the canvas * percentage; // type : string // Default : '40%'; Width: '100%', / / / / position 4 selected value: leftTop/leftBottom/rightTop/rightBottom; // type : string // Default : 'rightBottom'; Pos: 'leftTop', // margin of the distance from the canvas edge, // type: Number // Default: 20; margin : 20, }Copy the code

4,text(context,options):

Add a text function; Support for various styles, automatic wrapping; Added support for Stroke text, gradient text, text shadow;

Usage:

// Text content, support configuration of three font styles, big/normal/small; / / < b > < / b > : big word | < s > < / s > fine print: print | < br > : wrap the context: '<b> Big font Big font </b> Regular font <br> Newline <s> Small font small font </s>', options:{// Define the width value of each line of text, relative to the canvas; // example : width: 100 / '100%' / '100px'; Width: 300, // align of each line // 'left'/'center'/'right'; Align: 'left', / / by smallStyle/normalStyle/largeStyle configured respectively; // smallStyle // normalStyle/largeStyle; SmallStyle :{// Text style, including font/size, use the same way as CSS font; Font: ' ', // font color; Color :'#000', // lineheight: 100, // type, solid font or stroke font Type: 'fill' | 'stroke, / / when to stroke, the value control stroke width; {color: null, blur: 0, offsetX: 0, offsetY: 0,}, // gradient:{type: 2, // 1: horizontal gradient; 2: vertical gradient; ColorStop: ['red','blue'],},}, // position coefficient relative to canvas; // the position of text on canvas; Pos :{// Coordinates the starting point of the text relative to the canvas, the origin is the upper left point; / / support for multiple values: / / x: 250 / '250 px'/' 100% '/' left: 250 '/' center ', x: 0, y: 0, rotate: 0,,}};Copy the code

5,mc.rect(ops)

Like the add function, this method is used to draw a rectangle directly;

Ops: {// top left corner of rectangle, support multiple values; / / x: 250 / '250 px'/' 100% '/' left: 250 '/' center ', x: 0, y: 0, / / rectangle size; StrokeWidth: 1, // strokeColor: '# FFF ', // fillColor: '# FFF ',}Copy the code

6,mc.circle(ops)

Similar to recT function, this method is used to draw circles directly.

Ops: {// Circle center position, support various values; / / x: 250 / '250 px'/' 100% '/' left: 250 '/' center ', x: 0, y: 0, / / the circular radius; StrokeWidth: 1, // strokeColor: '# FFF ', // fillColor: '# FFF ',}Copy the code

6,mc.draw(ops):

Drawing function, add/watermark/text method need to call this method at the end of drawing, and this function includes export function, the base64 of the result graph can be directly obtained in the callback.

params:

// Base64 and configuration coefficients can only be fetched in this callback because of asynchron; Mc.draw ({// Export image format: PNG/JPG /jpeg/webp; // default : png; Type: 'PNG ', // image quality, invalid for PNG format; 0 ~ 1; // default: .9; Quality: 1, // Successful callback; success(b64){ console.log(b64); }, // Error callback; error(err){ console.log(err); }})Copy the code

Eight,clear():

You can empty the canvas at any time;

Expose properties

1.mc.canvasCanvas type:HTMLCanvasElement used by the canvas;
2,mc.ctx: the canvas;
3,mc.textData: text data type:object;