Fabricjs
made with React

Fabricjs

这是一个支持缩放拖拽旋转的组件

相关问答
暂无相关问题
查看全部
简介及使用教程

这是一个支持缩放拖拽旋转的组件。

特性

  • 开箱即用的交互,例如缩放、移动、旋转、倾斜、分组......
  • 内置形状、控件、动画、图像滤镜、渐变、图案、画笔......
  • JPG、 和 I/OPNG``JSON``SVG

安装

$ npm install fabric --save
// or
$ yarn add fabric

快速上手

// v6
import { Canvas, Rect } from 'fabric'; // browser
import { StaticCanvas, Rect } from 'fabric/node'; // node

// v5
import { fabric } from 'fabric';

纯HTML




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

ReactJs



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

NodeJs




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

示例

image.png

image.png

作者

Fabric.js

相关项目