[hidecontent type="logged" desc="隐藏内容:登录后可查看"]
Context | Supported Version | Notes |
---|---|---|
Firefox | ✔️ | modern version (tbd) |
Safari | ✔️ | version >= 10.1 |
Opera | ✔️ | chromium based |
Chrome | ✔️ | modern version (tbd) |
Edge | ✔️ | chromium based |
Edge Legacy | ❌ | |
IE11 | ❌ | |
Node.js | ✔️ | Node.js installation |
Fabric.js 默认不使用转译,我们支持的浏览器版本取决于我们要使用的canvas api的级别和一些js语法。虽然 JS 可以很容易地转换,但画布 API 不能。
v6 是一项重大工作,包括迁移到 TS 和 es6、无数修复、重写和功能。 目前处于测试阶段,请参阅#8299获取指导。
$ npm install fabric@beta --save
// or
$ yarn add fabric@beta
$ npm install fabric --save
// or
$ yarn add fabric
请参阅浏览器模块以在浏览器中使用 es6 导入或使用专用的捆绑器。
Fabric.js 依赖于node-canvas的画布实现(HTMLCanvasElement
替换)和jsdomwindow
的节点实现。这意味着您可能会遇到node-canvas
限制和错误。
按照这些说明启动node-canvas
并运行。
// v6
import { Canvas, Rect } from 'fabric'; // browser
import { StaticCanvas, Rect } from 'fabric/node'; // node
// v5
import { fabric } from 'fabric';
<canvas id="canvas" width="300" height="300"></canvas> <script src="https://cdn.jsdelivr.net/npm/fabric"></script> <script> const canvas = new fabric.Canvas('canvas'); const rect = new fabric.Rect({ top: 100, left: 100, width: 60, height: 70, fill: 'red', }); canvas.add(rect); </script>
import React, { useEffect, useRef } from 'react'; import * as fabric from 'fabric'; // v6 import { fabric } from 'fabric'; // v5 export const FabricJSCanvas = () => { const canvasEl = useRef<HTMLCanvasElement>(null); useEffect(() => { const options = { ... }; const canvas = new fabric.Canvas(canvasEl.current, options); // make the fabric.Canvas instance available to your app updateCanvasContext(canvas); return () => { updateCanvasContext(null); canvas.dispose(); } }, []); return <canvas width="300" height="300" ref={canvasEl}/>; };
import http from 'http'; import * as fabric from 'fabric/node'; // v6 import { fabric } from 'fabric'; // v5 const port = 8080; http .createServer((req, res) => { const canvas = new fabric.Canvas(null, { width: 100, height: 100 }); const rect = new fabric.Rect({ width: 20, height: 50, fill: '#ff0000' }); const text = new fabric.Text('fabric.js', { fill: 'blue', fontSize: 24 }); canvas.add(rect, text); canvas.renderAll(); if (req.url === '/download') { res.setHeader('Content-Type', 'image/png'); res.setHeader('Content-Disposition', 'attachment; filename="fabric.png"'); canvas.createPNGStream().pipe(res); } else if (req.url === '/view') { canvas.createPNGStream().pipe(res); } else { const imageData = canvas.toDataURL(); res.writeHead(200, '', { 'Content-Type': 'text/html' }); res.write(`<img src="${imageData}" />`); res.end(); } }) .listen(port, (err) => { if (err) throw err; console.log( `> Ready on http://localhost:${port}, http://localhost:${port}/view, http://localhost:${port}/download` ); });
[/hidecontent]