fabricjs

更新于

创建一个简单的矩形(react)

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

这里配置里面有个自定义属性customKey 在需要获取自定义key时,canvas的toObject方法是可以传递参数的

对象的初始化配置

import {Rect} from "fabric";
//直接通过配置的方式进行初始化
const rect = new Rect({
top:50,
left:50,
width:100,
height:100,
fill:'green',
customKey:'this is custom key',
})
//new 之后再初始化
const rect1 = new Rect()
rect1.set('fill', 'red');
rect1.set({ strokeWidth: 5, stroke: 'rgba(100,200,200,0.5)' });
rect1.set('angle', 15).set('flipY', true);

获取对象的属性

import {Rect} from "fabric";
const rect1 = new Rect()
rect1.set('fill', 'red');
rect1.set({ strokeWidth: 5, stroke: 'rgba(100,200,200,0.5)' });
rect1.set('angle', 15).set('flipY', true);
rect1.get('fill')

canvas对象