我对fabric.js很了解。我想在画布上绘制一个椭圆形。当我绘制它时,但是我无法选择它。我向对象添加了一个事件侦听器,该事件也未触发。
代码如下。
import { fabric } from 'fabric'
export class EllipseManager {
isDrawing = false
object: fabric.Ellipse
initPos: fabric.Point
constructor(
private canvas: fabric.Canvas
) {
this.canvas.setCursor('crosshair')
this.canvas.on('mouse:down', this.onMouseDown)
this.canvas.on('mouse:move', this.onMouseMove)
this.canvas.on('mouse:up', this.onMouseUp)
}
destroy() {
// unbind event
}
private onMouseDown = (option) => {
this.isDrawing = true
this.initPos = option.pointer
this.object = new fabric.Ellipse({
rx: 0,
ry: 0,
fill: 'red',
top: option.pointer.y,
left: option.pointer.x,
})
this.canvas.add(this.object)
// for test
this.object.on('mousedown', (e) => console.log(e))
console.log(this.object)
}
private onMouseMove = (event) => {
if (!this.isDrawing) return
const currentPos = event.pointer
const x = currentPos.x - this.initPos.x
const y = currentPos.y - this.initPos.y
this.object.setOptions({
rx: Math.abs(x/2),
ry: Math.abs(y/2)
})
// as x, y is smaller than 0 , so use '+'
if (x < 0) {
this.object.setOptions({
left: this.initPos.x + x,
})
}
if ( y < 0) {
this.object.setOptions({
top: this.initPos.y + y,
})
}
}
private onMouseUp = () => {
this.isDrawing = false
}
}
我搜索了很多演示,找不到与众不同的地方。
我的画布喜欢那张照片。这两个椭圆不能选择,并且事件绑定也不能触发。