Fabric.js 简单介绍和使用

来源:https://segmentfault.com/a/1190000004864237

简介

Fabric.js是一个可以简化canvas程序编写的库。 Fabric.js为canvas提供所缺少的对象模型, svg parser, 交互和一整套其他不可或缺的工具。基于MIT协议开源,在github上有许多人贡献代码。

Why fabric?

canvas提供一个好的画布能力, 但其api超级烂。如果你就想画个简单图形, 其实也可以, 不过做一些复杂的图形绘制, 编写一些复杂的效果,就不是那么好了。
fabric就是为此而开发。

用对象的方式去编写代码

举个例子
传统的画正方形代码

// reference canvas element (with id="c")
var canvasEl = document.getElementById('c');

// get 2d context to draw on (the "bitmap" mentioned earlier)
var ctx = canvasEl.getContext('2d');

// set fill color of context
ctx.fillStyle = 'red';

// create rectangle at a 100,100 point, with 20x20 dimensions
ctx.fillRect(100, 100, 20, 20);

使用fabric

// create a wrapper around native canvas element (with id="c")
var canvas = new fabric.Canvas('c');

// create a rectangle object
var rect = new fabric.Rect({
    left: 100,
    top: 100,
    fill: 'red',
    width: 20,
    height: 20
});

// "add" rectangle onto canvas
canvas.add(rect);

好的 其实并没有什么差别 不过我们试着旋转一下角度

var canvasEl = document.getElementById('c');
var ctx = canvasEl.getContext('2d');
ctx.fillStyle = 'red';

ctx.translate(100, 100);
ctx.rotate(Math.PI / 180 * 45);
ctx.fillRect(-10, -10, 20, 20);

fabric

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

// create a rectangle with angle=45
var rect = new fabric.Rect({
  left: 100,
  top: 100,
  fill: 'red',
  width: 20,
  height: 20,
  angle: 45
});

canvas.add(rect);

如果我们想重新调整位置 怎么办

var canvasEl = document.getElementById('c');

...
ctx.strokRect(100, 100, 20, 20);
...

// erase entire canvas area
ctx.clearRect(0, 0, canvasEl.width, canvasEl.height);
ctx.fillRect(20, 50, 20, 20);

fabric

var canvas = new fabric.Canvas('c');
...
canvas.add(rect);
...

rect.set({ left: 20, top: 50 });
canvas.renderAll();

objects

  1. fabric.Circle

  2. fabric.Ellipse

  3. fabric.Line

  4. fabric.Polygon

  5. fabric.Polyline

  6. fabric.Rect

  7. fabric.Triangle

画一个三角形 和一个 圆形

// create a wrapper around native canvas element (with id="c")
var canvas = new fabric.Canvas('c');

var circle = new fabric.Circle({
    radius: 20, fill: 'green', left: 100, top: 100
});
var triangle = new fabric.Triangle({
    width: 20, height: 30, fill: 'blue', left: 50, top: 50
});

canvas.add(circle, triangle);

Manipulating objects

可以简单的使用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.

rect.set('fill', 'red');
rect.set({ strokeWidth: 5, stroke: 'rgba(100,200,200,0.5)' });
rect.set('angle', 15).set('flipY', true);

有了set 其实也就有了get

对象可以创建时设置属性 也可以先实例化 再赋值

var rect = new fabric.Rect({ width: 10, height: 20, fill: '#f55', opacity: 0.7 });

// or functionally identical

var rect = new fabric.Rect();
rect.set({ width: 10, height: 20, fill: '#f55', opacity: 0.7 });

另外这里的fabric.Rect是函数 大家可以使用class继承

默认值

var rect = new fabric.Rect(); // notice no options passed in

rect.getWidth(); // 0
rect.getHeight(); // 0

rect.getLeft(); // 0
rect.getTop(); // 0

rect.getFill(); // rgb(0,0,0)
rect.getStroke(); // null

rect.getOpacity(); // 1

Hierarchy and Inheritance

fabric.Object 是图像基类

你可以自己扩充方法

fabric.Object.prototype.getAngleInRadians = function() {
  return this.getAngle() / 180 * Math.PI;
};

var rect = new fabric.Rect({ angle: 45 });
rect.getAngleInRadians(); // 0.785...

var circle = new fabric.Circle({ angle: 30, radius: 10 });
circle.getAngleInRadians(); // 0.523...

circle instanceof fabric.Circle; // true
circle instanceof fabric.Object; // true

Canvas

fabric.Canvas 是canvas的wrapper

var canvas = new fabric.Canvas('c');
var rect = new fabric.Rect();

canvas.add(rect); // add object

canvas.item(0); // reference fabric.Rect added earlier (first object)
canvas.getObjects(); // get all objects on canvas (rect will be first and only)

canvas.remove(rect); // remove previously-added fabric.Rect

经典的设计 有options 有对象方法

var canvas = new fabric.Canvas('c', {
  backgroundColor: 'rgb(100,100,200)',
  selectionColor: 'blue',
  selectionLineWidth: 2
  // ...
});

// or

var canvas = new fabric.Canvas('c');
canvas.setBackgroundImage(http://...');
canvas.onFpsUpdate = function(){ /* ... */ };
// ...

Images

使用fabric.Image你可以轻松的加载一个图片
html

<canvas id="c"></canvas>
<img src="my_image.png" id="my-image">

js

var canvas = new fabric.Canvas('c');
var imgElement = document.getElementById('my-image');
var imgInstance = new fabric.Image(imgElement, {
  left: 100,
  top: 100,
  angle: 30,
  opacity: 0.85
});
canvas.add(imgInstance);

当然也可以通过url加载一张图片到canvas

fabric.Image.fromURL('my_image.png', function(oImg) {
  canvas.add(oImg);
});

可以对加载的图片进行预处理

fabric.Image.fromURL('my_image.png', function(oImg) {
  // scale image down, and flip it, before adding it onto canvas
  oImg.scale(0.5).setFlipX(true);
  canvas.add(oImg);
});

Path and PathGroup

我们已经看了简单的形状,然后图像。更复杂、丰富的形状和内容呢?
路径包括一系列的命令,这基本上模仿一个笔从一个点到另一个。在“移动”,“线”,“曲线”,或“弧”等命令的帮助下,路径可以形成令人难以置信的复杂形状。同组的路径(路径组的帮助),开放更多的可能性。
类似于svg的path

var canvas = new fabric.Canvas('c');
var path = new fabric.Path('M 0 0 L 200 100 L 170 200 z');
path.set({ left: 120, top: 120 });
canvas.add(path);

“M” 代表 “move” 命令, 告诉笔到 0, 0 点.
“L” 代表 “line” 画一条0, 0 到 200, 100 的线. 
another “L” creates a line to 170, 200.
z” tells forces drawing pen to close current path and finalize the shape.

...
var path = new fabric.Path('M 0 0 L 300 100 L 200 300 z');
...
path.set({ fill: 'red', stroke: 'green', opacity: 0.5 });
canvas.add(path);

path也可以设置canvas属性

当然 太困然了 所以你可以使用 fabric.loadSVGFromString or fabric.loadSVGFromURL 方法

展开阅读全文

没有更多推荐了,返回首页