介绍:
Fabric.js是一个强大且灵活的JavaScript HTML5 canvas库。它允许你通过一种友好且易于使用的方法创建和处理对象。以下是一些Fabric.js的主要特性:
总的来说,Fabric.js是一个非常强大的库,用于创建和处理HTML5 canvas图形。它的友好性和易用性使得开发者可以快速上手并创建出复杂的图形和动画。
fabric官网:
Fabric.js Javascript Canvas Library
react中安装使用:
npm install fabric
创建画布:
import React, { useEffect, useRef, useState } from 'react';
import { fabric } from 'fabric';
export default function App() {
const canvasRef = useRef(null);
const [canvas, setCanvas] = useState(null);
return (
);
}
创建图形:
const rect = new fabric.Rect({
left: 100,
top: 50,
fill: 'pink',
width: 60,
height: 60,
strokeWidth: 5,
hasControls: true,
hasRotatingPoint: true,
hasBorders: true,
transparentCorners: true,
perPixelTargetFind: true,
selectable: true,
lockMovementX: false,
lockMovementY: false,
});
const circle = new fabric.Circle({
left: 100,
top: 100,
fill: 'yellow',
radius: 50,
});
newCanvas.add(circle);
导入图片:
fabric.Image.fromURL('images/logo192.png', function (oImg) {
// scale image down, and flip it, before adding it onto canvas
//缩小图像并翻转它
oImg.scale(0.5).set('flipX', true);
newCanvas.add(oImg);
});
全部代码:
import React, { useEffect, useRef, useState } from 'react';
import { fabric } from 'fabric';
export default function App() {
const canvasRef = useRef(null);
const [canvas, setCanvas] = useState(null);
useEffect(() => {
const newCanvas = new fabric.Canvas(canvasRef.current, {
backgroundColor: '#fffffb',
width: 768,
height: 576,
});
setCanvas(newCanvas);
const rect = new fabric.Rect({
left: 100,
top: 50,
fill: 'pink',
width: 60,
height: 60,
strokeWidth: 5,
hasControls: true,
hasRotatingPoint: true,
hasBorders: true,
transparentCorners: true,
perPixelTargetFind: true,
selectable: true,
lockMovementX: false,
lockMovementY: false,
});
const circle = new fabric.Circle({
left: 100,
top: 100,
fill: 'yellow',
radius: 50,
});
newCanvas.add(circle);
newCanvas.add(rect);
fabric.Image.fromURL('images/logo192.png', function (oImg) {
// scale image down, and flip it, before adding it onto canvas
//缩小图像并翻转它
oImg.scale(0.5).set('flipX', true);
newCanvas.add(oImg);
});
return () => {
// newCanvas.dispose();
};
}, [canvasRef]);
return (
);
}