FabricJS使用小结 -- 初步认识

368 阅读2分钟

简介

什么是 Fabric.js

Fabric.js是一个可以简化Canvas程序编写的库。Canvas提供一个好的画布能力, 但是Api不够友好。绘制简单图形其实还可以, 不过做一些复杂的图形绘制, 编写一些复杂的效果,就不是那么方便了。Fabric.js就是为此而开发,它主要就是用对象的方式去编写代码。

举例

传统的画正方形代码

// 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);

试着旋转一下角度

传统的

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);

如果我们想重新调整位置

传统的

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

Fabric的

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来控制对象属性

  1. positioning — left, top;
  2. dimension — width, height;
  3. rendering — fill, opacity, stroke, strokeWidth;
  4. scaling and rotation — scaleX, scaleY, angle;
  5. 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);

参考

  1. 官网地址

联系我

库使用过程有什么问题,可以跟我沟通,加我的wx:meetbc。欢迎交流关于前端的任何话题。