0

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


我搜索了很多演示,我找不到不同的地方。

在此处输入图像描述

我的画布喜欢那幅画。这两个椭圆不能选择并且不能触发事件绑定。

4

0 回答 0