监听事件

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

ts

  1. import { Leafer, Rect, PointerEvent } from 'leafer-ui'
  2. const leafer = new Leafer({ view: window })
  3. const rect = new Rect({
  4. x: 100,
  5. y: 100,
  6. width: 200,
  7. height: 200,
  8. fill: '#32cd79', // 背景色
  9. stroke: 'black', // 边框
  10. strokeWidth: 2, // 边框粗细
  11. draggable: true
  12. })
  13. leafer.add(rect)
  14. function onEnter(e: PointerEvent) {
  15. (e.current as Rect).fill = '#42dd89'
  16. }
  17. function onLeave(e: PointerEvent) {
  18. (e.current as Rect).fill = '#32cd79'
  19. }
  20. rect.on(PointerEvent.ENTER, onEnter)
  21. rect.on(PointerEvent.LEAVE, onLeave)

使用字符串

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

ts

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

移除事件

ts

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

派发事件

ts

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

恭喜 🎉

你已完成基础知识的学习,接下来将学习几个重要的进阶知识。