Skip to content

事件处理

监听事件

为矩形添加鼠标进入/离开事件效果:

ts
import { Leafer, Rect, PointerEvent } from 'leafer-ui'

const leafer = new Leafer({ view: window })

const rect = new Rect({
    x: 100,
    y: 100,
    width: 200,
    height: 200,
    fill: '#32cd79', // 背景色
    stroke: 'black', // 边框
    strokeWidth: 2, // 边框粗细
    draggable: true
})

leafer.add(rect)


function onEnter(e: PointerEvent) {
    (e.current as Rect).fill = '#42dd89'
}

function onLeave(e: PointerEvent) {
    (e.current as Rect).fill = '#32cd79'
}

rect.on(PointerEvent.ENTER, onEnter)
rect.on(PointerEvent.LEAVE, onLeave)
js
import { Leafer, Rect, PointerEvent } from 'leafer-ui'

const leafer = new Leafer({ view: window })

const rect = new Rect({
    x: 100,
    y: 100,
    width: 200,
    height: 200,
    fill: '#32cd79', // 背景色
    stroke: 'black', // 边框
    strokeWidth: 2, // 边框粗细
    draggable: true
})

leafer.add(rect)


function onEnter(e) {
    e.current.fill = '#42dd89'
}

function onLeave(e) {
    e.current.fill = '#32cd79'
}

rect.on(PointerEvent.ENTER, onEnter)
rect.on(PointerEvent.LEAVE, onLeave)

还支持初始化传入 event 对象,用于快速监听事件:

ts
import { Leafer, Rect, PointerEvent } from 'leafer-ui'

const leafer = new Leafer({ view: window })

const rect = Rect.one({
    fill: '#32cd79',
    draggable: true,
    event: {
        [PointerEvent.ENTER]: function (e: PointerEvent) {
            (e.current as Rect).fill = '#42dd89'
        },
        [PointerEvent.LEAVE]: function (e: PointerEvent) {
            (e.current as Rect).fill = '#32cd79'
        }
    }
}, 100, 100, 200, 200)

leafer.add(rect)
js
import { Leafer, Rect, PointerEvent } from 'leafer-ui'

const leafer = new Leafer({ view: window })

const rect = Rect.one({
    fill: '#32cd79',
    draggable: true,
    event: {
        [PointerEvent.ENTER]: function (e) {
            e.current.fill = '#42dd89'
        },
        [PointerEvent.LEAVE]: function (e) {
            e.current.fill = '#32cd79'
        }
    }
}, 100, 100, 200, 200)

leafer.add(rect)

使用字符串

了解事件类型的字符串命名规则

ts
rect.on('pointer.enter', onEnter)
rect.on('pointer.leave', onLeave)

移除事件

ts
rect.off('pointer.enter', onEnter)
rect.off('pointer.leave', onLeave)

派发事件

ts
rect.emit('pointer.enter', { current: rect })

下一步

移除内容

Released under the MIT License.