import {Canvas,Rect} from 'fabric'
import {useEffect} from "react";
export default function HelloFabric(){
let canvas=null
const rect = new Rect({
top:50,
left:50,
width:100,
height:100,
fill:'green',
customKey:'this is custom key',
selectable:false
})
useEffect(()=>{
// 实例化canvas
canvas = new Canvas('cvs')
// 往canvas里添加配置好的矩形
canvas.add(rect)
// 将fabricjs的配置导出,并且导出自定义的key 'customKey'
console.log(canvas.toObject(['customKey']))
return ()=>{
// 退出清除
canvas.destroy()
}
},[])
const onChangeRect = ()=>{
rect.set({
width:200,
fill:'red'
})
// 修改之后需要重新render否则不生效
canvas?.renderAll()
}
return <div>
<canvas id='cvs' width={400} height={400} style={{border:'1px solid #f00'}}></canvas>
<button onClick={onChangeRect}>修改Rect</button>
</div>
}