Fabric 是基于 HTML5 canvas 的图形库,通过操作对象的属性来操作 canvas (叫 object model),已经提供了一些基本的图元,如 Rect, Circle, Ellipse, Line, Polygon, Image, SVG, Text, Textbox, 阴影等,支持动画、拖动放大缩小旋转等,还支持自由绘制,能够序列化为字符串方便保存,需要的时候再把字符串反序列化为 fabric.Canvas 对象。
Fabric.js is a powerful and simple Javascript HTML5 canvas library. Fabric provides interactive object model on top of canvas element. Fabric also has SVG-to-canvas (and canvas-to-SVG) parser.
下面列举一些可能会常用到的知识点:
- 全局设置默认值:
fabric.Object.prototype.transparentCorners = false
(cornerSize: 7)
- 导出时包含指定 / 自定义属性:
canvas.toJSON(['name', 'lockScalingY']
,默认很多属性都没有到处,根据自己的需要在这里指定
- 设置选中 item 的属性:
canvas.getActiveObject().set("fontFamily", 'Monaco')
- 修改整个 canvas 的鼠标:
canvas.defaultCursor = 'move'
<canvas width="100" height="100">
的大小被 Canvas 中指定的值覆盖: new fabric.Canvas('c', { width: 600, height: 600 })
- 控制点 controls 指的是选中图形后在图形边框上出现的 8 个用来控制图形大小的小方框,名字为 tl, tr, br, bl, ml, mt, mr, mb
canvas.renderAll()
会立即重绘,canvas.requestRenderAll()
则是把重绘的命令放到事件队列里,如果准备放入时已经存在则丢弃,不重复放入队列中
- 常用属性: Well, as you would expect there are those related to
- positioning: left, top
- dimension: width, height
- rendering: fill, opacity, stroke, strokeWidth
- scaling and rotation: scaleX, scaleY, angle
- flipping: flipX, flipY
- skewing: skewX, skewY
在 Fabric Demos 里有很多例子,对学习 Fabric 非常有帮助。