Fabric Learning Notes

Source: Internet
Author: User
Tags html tags object model tojson

The Learning definition of Fabric

Fabric provides a missing object model Forcanvas, as as a SVG parser, layer of interactivity, and a whole suite ofot  Her indispensable tools. function

The object model is provided on the base of the canvas

Provides the basic types of canvas rendering and state management objects :

Fabric. Circle

Fabric. Ellipse

Fabric. Line

Fabric. Polygon

Fabric. Polyline

Fabric. Rect

Fabric. Triangle Action object:

Property Get (' width ') and set ({}): positioning- left, top; dimension- width, height; rendering- fill, opacity, stroke,strokewidth; Scaling and rotation- ScaleX, scaleY, angle; And even those related to flipping- flipx, flipy.

Action when state changes: implemented by event

Animation Hierarchy Relationship:

Fabric. Object: Represents a two-dimensional shape with attributes Left/top and Width/height properties, as good as a slew of other graphiccharacteristics. Those properties that we saw on objects-fill, stroke, angle, opacity, flip*, etc. can be in fabric. Object.prototype defines functions, in fabric. Shared on subclasses of object

Fabric. Circle has RADIUS attributes

Fabric. Image has setelement and getelement Canvas

is a <canvas> packaging class that manages all fabric. Object

There are methods: Add GetObjects Item Remove.

Configuration: Background color or background picture, cut, interactive, etc.

Interactive:

Support:

Select, drag, rotate, zoom in, group together actions

Steps:

Initialize canvas, Load object model

Use the selection and selectable properties Canvas.selection = false;//Disable Group selection rect.set (' selectable ', false); Makeobject unselectable

Create a canvas with no interaction (lightweight)

var Staticcanvas = newfabric. Staticcanvas (' C ');

Staticcanvas.add (.....) ) Images

When you have HTML tags: use fabric. Image

When there is a URL: fabric. Image.fromurl, the parameter in the callback function is the fabric. Image path and Pathgroup

Make any vector graph

Path includes a series of commands, such as "move", "line", "curve", or "arc", similar to SVG <path>, which uses fabric. Path to create manually, step:

Varpath=new fabric. Path

Path.set

You can also use the fabric built-in SVG parser to create (really create complex graphics, which is a lot more), step:

Using fabric.loadsvgfromstring loadsvgfromurl to load the entire SVG

Using SVG parser to get the path object

Pathgroup is a collection of path, integrated into fabric. Object, so you can add it to the Cavas.

Animation

Use the Animate function, which includes three parameters: properties, values (supporting target values, such as 300, relative values, such as ' +=100 '), callback functions (support for duration, from,oncomplete, easing change, and so on, generally listening for change events.) )

OnChange:canvas.renderAll.bind (canvas) is rendered as each frame changes to see the animation effect

Easing represents the change function, the desirable value is fabric.util.ease under the package, there are easeoutbounce easeincubic easeoutcubiceaseinelastic Easeinbounce and Easeoutexpo Filter:

Picture filter effect, pre-supported with remove Whitebackground grayscale filter Invert or brigtness one, gradienttransparentcy, sepia, noise

Use fabric. Image.filters.push, then call Img.applyfilters (Canvas.renderAll.bind (canvas));

Supported remove filter (via pop, splice, or shift), add filter (via Push, splice, unshift), or even combine m Ultiple filters.

Customizable filter: Slightly, refer to the corresponding section in filter Color:

supports a variety of color definitions, such as RGB RGBA hex, etc.

Newfabric. Color (' #123123 ');

Newfabric. Color (' RGB (100,0,100) '); gradients

Use the Setgradientfil function in object, such as

Circle.setgradientfill ({

x1:0,

y1:0,

x2:0,

Y2:circle.height,

ColorStops: {

0: ' #000 ',

1: ' #fff '

}

});

Where X1,y1 defines the start point, X2,y2 defines the end point, ColorStops can have multiple, from 0 to 1 (e.g. 0, 0.1, 0.3, 0.5, 0.75, 1), such as Rainbow Seven colors

Text (WordArt) Extensions: Multiline support. Native text Methods Unfortunately simply ignore new lines. Text Alignment. Left, center, right. Useful when working with multiline text. Text background. Background also respects text alignment. Text decoration. Underline, Overline, Strike-through. Line height. Useful when working with multiline text

such as: var text = newfabric. Text (' Hello World ', {left:100, top:100});

The second parameter is optional, which can be left, top, fill, opacity,fontfamily, FontSize fontweight Textshadow, fontstyle strokestyle text BackgroundColor lineheight textAlign. Events

Provides an object event from low-end mouse to high-end, such as:

Mouse-level:

"mouse:down", "mouse:move", and "mouse:up".

Genericones:

"after:render".

Selection-related:

"before:selection:cleared", "selection:created", "selection:cleared".

Object ones:

"object:modified", "object:selected", "object:moving", "object:scaling", " Object:rotating", and"object:added".

Use on listener event, off to remove listener

Note this eventslike "object:moving" (or "object:scaling") are fired Continuouslyevery time an object is moved (or scaled) Even by one pixel. On the other hand,events like "object:modified" or "selection:created" arefired only at the end of the action (object Modi Fication or Selectioncreation).

You can also add Event Canvas.on (' Mouse:down ', function (options) {Console.log (Options.e.clientx, Options.e.clienty) directly to model object. ;    }); Where the options have two attributes, an e represents the event, and target represents the object emitted by the event Groups

Uniform movement and modification of multiple objects (scale rotate, etc.)

Create a Labeledeclipse

var group = new fabric. Group ([text,circle], {

left:150,

TOP:100,

Angle:-10

});

Canvas.add (group);

Modify an individual in a group

Group.item (0). Set ({

Text: ' Trololo ',

Fill: ' White '

});

Group.item (1). Setfill (' red ');

The item default layout in group is in the center of the group by setting the left and top properties for each item to modify

Other functions: GetObjects () gets all objects in the group, item gets a single object, etc.

To create a group of objects already loaded in canvas

var group = new fabric. Group ([

Canvas.item (0). Clone (),

Canvas.item (1). Clone ()

]);

Remove all objects and Re-render

Canvas.clear (). Renderall ();

Add group onto canvas

Canvas.add (group); Serialization

Used to pass data to other clients and servers. Toobject,tojson in text mode

where Toobject is converted to object format and Tojson to JSON strings

Instance:

Converting an object to a string

var canvas = new fabric. Canvas (' C ');

Json.stringify (canvas); ' {"Objects": [], "Background": "Rgba (0,0, 0, 0)"} '

For custom classes, just define the Toobject function, which can be called recursively when using Canvas.toobject (), similar to Java ToString. Tosvg

Another text format for canvas is that the resulting text can be parsed by an external SVG program,

deserialization,svg Parser

Fabric. Canvas#loadfromjson corresponds to the above Canvas.tojson ();

Fabric. Canvas#loadfromdatalessjson is used to load complex graphics, such as path, corresponding to Canvas.todatalessjon (), you need to set sourcepath for graphics, such as:

Canvas.item (0). SourcePath = '/assets/dragon.svg ';

Console.log (Json.stringify (Canvas.todatalessjson ()));

Fabric.loadsvgfromurl and Fabric.loadsvgfromstring

Fabric.loadsvgfromstring (' ... '), function (objects, options) {

Varobj = Fabric.util.groupSVGElements (objects, options);

Canvas.add (obj). Renderall ();

});

subclassing

Supports subclass extensions of objects, slightly free drawing

Supports any painting on the canvas, step:

1.canvas.isdrawingmode (true) the mouse movement is considered pen and brush.

2. When mouse:up, the fabric emits path:created events and creates fabric. Path instance

3. Canvas.isdrawingmode (false) to terminate painting

You can set the canvas freedrawingcolor and Freedrawinglinewidth

Customization

Set parameters for canvas and its objects

Lockingobjects: such as obj.lockrotation=true; Can be set "Lockmovementx", "Lockmovementy", "Lockrotation", "lockscaling"

Changeborder corners:hasborders hascontrols bordercolor cornercolor cornersize

Disablingselection:canvas.selection is valid for all, obj.selectable is valid for single

Customizingselection: Modify the selected style "SelectionColor", "Selectionbordercolor", "Selectionlikewidth", and

"Selectiondasharray"

Dashedstroke: Stroke style of edges

Clickablearea:

Rotatingpoint

Objecttransformation:uniscaletransform

Canvasbackground and Overlay:backgroundcolor, backgroundimagesetoverlayimage (topmost image) Fabric on Node.js

Can let JS run on the server, such as sending data, generate pictures on the server. Reference:

http://fabricjs.com/fabric-intro-part-1/#objects

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.