Fabric 的学习
定义
Fabric.js provides a missing object model for canvas, as well as an SVG parser, layer of interactivity, and a whole suite ofother indispensable tools.
作用
在canvas的底层基础上提供了 object model
提供 canvas的 rendering和state管理
对象
基本类型:
fabric.Circle
fabric.Ellipse
fabric.Line
fabric.Polygon
fabric.Polyline
fabric.Rect
fabric.Triangle
操作对象:
属性 get('width')和 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.
状态变化时的动作:通过event来实现
动画
层次关系:
fabric.Object: 代表二维形状,具有属性 left/top and width/height properties, as well as a slew of other graphiccharacteristics. Those properties that we saw on objects — fill, stroke, angle, opacity, flip*, etc。 可以在fabric.Object.prototype 定义函数,在fabric.Object的子类上共享
fabric.Circle 有 radius属性
fabric.Image 有 setElement和getElement
Canvas
是<canvas>的包装类,管理所有的fabric.Object
有方法: add getObjects item remove.
配置:背景色或背景图片,剪切,是否交互等。
Interactive:
支持:
选择、拖动、旋转、放大、group together的操作
步骤:
初始化 canvas,加载 object model
使用 selection 和selectable属性 canvas.selection = false;// disable group selection rect.set('selectable', false); // makeobject unselectable
创建一不含交互的canvas(轻量级)
var staticCanvas = newfabric.StaticCanvas('c');
staticCanvas.add(。。。)
Images
有<img> html标签时:使用 fabric.Image
有 url 时: fabric.Image.fromUrl, 回调函数中的参数就是fabric.Image
Path和PathGroup
制作任意向量图
path 包括一系列的命令,如 “move”, “line”, “curve”, or “arc”, 类似于 svg 的<path> ,可使用 fabric.Path手动创建,步骤:
varpath=new fabric.Path
path.set
也可使用 fabric内置的 SVG Parser创建(真创建复杂图形,这种方法比较多),步骤:
使用 fabric.loadSVGFromString loadSVGFromURL加载整个SVG
使用 SVG Parser得到 path对象
PathGroup是Path的集合,集成于fabric.Object,所以可以add到cavas中
Animation
使用 animate 函数,包括三个参数:属性、值(支持目标值,如300, 相对值,如'+=100')、回调函数(支持 duration, from,onComplete, easing change等,一般监听change事件。 )
onChange: canvas.renderAll.bind(canvas) 在每帧变化时重新渲染,可看到动画效果
easing 代表变化函数,可取的值是fabric.util.ease包下,有easeOutBounce easeInCubic easeOutCubiceaseInElastic easeOutElastic easeInBounce 和easeOutExpo
Filter:
图片滤镜效果,预支持的有 remove whitebackground grayscale filter invert or brigtness one , gradienttransparentcy, sepia, noise
使用fabric.Image.filters.push ,再调用 img.applyFilters(canvas.renderAll.bind(canvas));
支持的 remove filter (via pop, splice, or shift), add filter (via push, splice, unshift), or even combine multiple filters.
可自定义filter: 略,参考filter中相应章节
Color:
支持多种color的定义,如rgb rgba hex等
newfabric.Color('#123123');
newfabric.Color('rgb(100,0,100)');
Gradients
使用Object 中的setGradientFil函数,如
circle.setGradientFill({
x1:0,
y1:0,
x2:0,
y2:circle.height,
colorStops: {
0:'#000',
1:'#fff'
}
});
其中 x1,y1定义开始点,x2,y2定义结束点,colorStops 可以有多个,从 0 to 1 (e.g. 0, 0.1, 0.3,0.5, 0.75, 1),如彩虹七色
Text(艺术字)
扩展:
- 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
如:var text = newfabric.Text('hello world', { left: 100, top: 100 });
其中第二个参数可选,可以为left, top, fill, opacity,fontFamily ,fontSize fontWeight textShadow, fontStyle strokeStyle strokeWidth textBackgroundColor lineHeight textAlign.
Events
提供从低端的mouse到高端的object 事件,如:
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"..
使用 on 监听事件,off 移除监听器
Note that 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 modification or selectioncreation).
也可以直接给 model object 添加事件 canvas.on('mouse:down', function(options){console.log(options.e.clientX, options.e.clientY); }); 其中options有两个属性,一个e 代表事件,target 代表事件发出的对象
Groups
对多个物体统一移动和修改(scale rotate等)
//创建一个 labeledeclipse
var group = new fabric.Group([ text,circle ], {
left:150,
top:100,
angle: -10
});
canvas.add(group);
//修改group中的个体
group.item(0).set({
text:'trololo',
fill:'white'
});
group.item(1).setFill('red');
group中item默认布局在group中央,通过给每个item设置left和top属性可修改
其他函数: getObjects() 获得group中所有对象, item 取得单个对象 等
创建已经在 canvas中加载的对象的group
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
用于传递数据到其他客户端和服务器。以text方式
toObject,toJSON
其中 toObject 转化为object格式,toJSON转换为json 字符串
实例:
//将对象转为字符串
var canvas = new fabric.Canvas('c');
JSON.stringify(canvas); // '{"objects":[],"background":"rgba(0,0, 0, 0)"}'
对于自定义类,只要定义 toObject函数,当使用 canvas.toObject()时就可以递归调用,类似于Java的toString。
toSVG
canvas的另一种文本格式,好处是生成的文本可以被外部的SVG程序解析,
Deserialization,SVG parser
fabric.Canvas#loadFromJSON 对应 上面的canvas.toJSON();
fabric.Canvas#loadFromDatalessJSON用于加载复杂图形,如带path的,对应 canvas.toDatalessJON() ,需要对图形设置sourcePath,如:
canvas.item(0).sourcePath ='/assets/dragon.svg';
console.log(JSON.stringify(canvas.toDatalessJSON()));
fabric.loadSVGFromURL和fabric.loadSVGFromString
fabric.loadSVGFromString('...',function(objects, options) {
varobj = fabric.util.groupSVGElements(objects, options);
canvas.add(obj).renderAll();
});
Subclassing
支持对象的子类化扩展,略
Free drawing
支持在canvas上任意画,步骤:
1.canvas.isDrawingMode(true)后将鼠标的移动认为是pen和brush。
2. 当mouse:up后,fabric发出 path:created事件,并创建fabric.Path实例
3. canvas.isDrawingMode(false)终止绘画
可设置canvas的 freeDrawingColor and freeDrawingLineWidth
Customization
设置canvas及其对象的参数
Lockingobjects:如obj.lockRotation=true; 可设置"lockMovementX", "lockMovementY", "lockRotation","lockScaling"
Changeborder corners: hasBorders hasControls borderColor cornerColor cornerSize
Disablingselection: canvas.selection 对所有有效 ,obj.selectable对单个有效
customizingselection: 修改选中样式 "selectionColor", "selectionBorderColor","selectionLikeWidth", and
"selectionDashArray"
dashedstroke:边的stroke样式
clickablearea:
rotatingpoint
objecttransformation:uniScaleTransform
canvasbackground和overlay:backgroundColor, backgroundImagesetOverlayImage(最上层图像)
Fabric on Node.js
可以让js在服务器上运行,如发送数据,在服务器上生成图片。
参考:
http://fabricjs.com/fabric-intro-part-1/#objects