我尝试使用 useEffect 将 SVG 渲染到画布上,如下所示:
// store canvas reference
const [canvas, setCanvas] = useState<fabric.Canvas>();
useEffect(() => {
const c = new fabric.Canvas("canvas", {
height: 700,
width: 700,
backgroundColor: "white",
});
setCanvas(c);
c.renderAll();
return () => {
c.dispose();
};
}, []);
useEffect(() => {
fabric.loadSVGFromURL('/example.svg', (objects, options) => {
const svg = fabric.util.groupSVGElements(objects, options);
// Add the SVG to the canvas and render
canvas?.add(svg);
canvas?.renderAll();
})
// wait for canvas to mount first
}, [canvas]);
但是画布上没有渲染任何内容,我在网上没有找到类似的项目,并且不知道使用react加载SVG的正确做法。我做错了什么?
好吧,你的代码看起来不错,但如果你无法使用 Fabric.js 加载 svg,你可以确认几件事。
我做了一个简单的 React 项目来展示如何使用 Fabric.js 加载 svg。我提供示例代码。
import { useEffect, useRef, useState } from 'react';
import { fabric } from 'fabric';
const FabricPanel = () => {
// States for Canvas
const canvasRef = useRef(null);
const [canvas, setCanvas] = useState(null);
useEffect(() => {
if (canvasRef.current) {
const fabricCanvas = new fabric.Canvas(canvasRef.current, {
fireMiddleClick: true,
stopContextMenu: true,
selection: true,
preserveObjectStacking: true
});
setCanvas(fabricCanvas);
fabricCanvas.backgroundColor = '#131313';
fabricCanvas.renderAll();
return () => {
fabricCanvas.dispose();
};
}
}, []);
// Load and center SVG on the canvas
useEffect(() => {
if (canvas) {
fabric.loadSVGFromURL('/images/bnb.svg', (objects, options) => {
const svg = fabric.util.groupSVGElements(objects, options);
// Add the SVG to the canvas and render
canvas?.add(svg);
canvas?.renderAll();
});
}
}, [canvas]);
return (
<div style={{ width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
<canvas ref={canvasRef} width="800" height="600" />
</div>
);
};
export default FabricPanel;
您可以在这里找到这个项目:Github,Stackblitz