概述

在canvas中模拟鼠标点击和移动事件,是将canvas中的绘画元素看做dom中的dom对象,借助浏览器中的坐标系与canvas本身的坐标系形成事件系统的坐标系,通过判断绘画对象的坐标,来在鼠标点击对应的绘画元素的时候进行对应的事件反馈。

一、 创建事件对象类

模拟dom中的事件对象,记录canvas鼠标事件中对应的信息

  1. class Event {
  2. constructor(x = -1, y = -1, type = null, target = null) {
  3. this.x = x
  4. this.y = y
  5. this.type = type
  6. this.target = target
  7. }
  8. }

模拟dom元素类,赋予绑定事件的能力

  1. class EventTarget {
  2. constructor(ctx) {
  3. this.ctx = ctx
  4. this._listeners = {}
  5. this.inBounds = false
  6. }
  7. hasListener(type) {
  8. if (this._listeners.hasOwnProperty(type)) {
  9. return true
  10. } else {
  11. return false
  12. }
  13. }
  14. addListener(type, listener) {
  15. if (!this._listeners.hasOwnProperty(type)) {
  16. this._listeners[type] = []
  17. }
  18. this._listeners[type].push(listener)
  19. this.ctx.eventManager.addTarget(type, this)
  20. }
  21. emit(type, event) {
  22. if (!event || !event.type) {
  23. return
  24. }
  25. if (this._listeners[event.type] instanceof Array) {
  26. let listeners = this._listeners[event.type]
  27. for (let i = 0, len = listeners.length; i < len; i++) {
  28. listeners[i].call(this, event)
  29. }
  30. }
  31. }
  32. removeListener(type, listener) {
  33. if (!listener) {
  34. if (this._listeners.hasOwnProperty(type)) {
  35. this._listeners[type] = []
  36. this.ctx.eventManager.removeTarget(type, this)
  37. }
  38. }
  39. if (this._listeners[type] instanceof Array) {
  40. let listeners = this._listeners[type]
  41. for (let i = 0, len = listeners.length; i < len; i++) {
  42. if (listeners[i].toString() === listener.toString()) {
  43. listeners.splice(i, 1)
  44. if (listeners.length === 0) this.ctx.eventManager.removeTarget(type, this)
  45. break
  46. }
  47. }
  48. }
  49. }
  50. }

二、 创建事件总线

如浏览器环境就是dom对象的管理总线一样,在canvas中,我们也需要创建出一个管理事件的总线

  1. class EventManager {
  2. constructor(ctx) {
  3. this.ctx = ctx
  4. this._targets = {}
  5. this._childs = []
  6. }
  7. getTargets(type) {
  8. if (!type) return
  9. type = this._getPrefix(type)
  10. return this._targets[type]
  11. }
  12. addTarget(type, target) {
  13. if (!type) return
  14. type = this._getPrefix(type)
  15. if (!this._targets.hasOwnProperty(type)) {
  16. this._targets[type] = new SortArray()
  17. }
  18. let array = this._targets[type]
  19. if (!array.contains(target)) {
  20. array.add(target)
  21. }
  22. }
  23. removeTarget(type, target) {
  24. if (!type) return
  25. type = this._getPrefix(type)
  26. if (!this._targets.hasOwnProperty(type)) {
  27. return
  28. }
  29. let array = this._targets[type]
  30. array.delete(target)
  31. }
  32. enableMove() {
  33. this.ctx.canvas.addEventListener('mousemove', event => this._handleMouseMove(event, this), false)
  34. }
  35. enableClick() {
  36. this.ctx.canvas.addEventListener('click', event => this._handleClick(event, this), false)
  37. }
  38. addChild(drawObject) {
  39. this._childs.push(drawObject)
  40. }
  41. _getPrefix(type) {
  42. if (type.indexOf('mouse') !== -1) {
  43. return 'mouse'
  44. }
  45. if (type.indexOf('click') !== -1) {
  46. return 'click'
  47. }
  48. return type
  49. }
  50. _windowToCanvas(x, y) {
  51. let bbox = this.ctx.canvas.getBoundingClientRect()
  52. return {
  53. x: x - bbox.left,
  54. y: y - bbox.top
  55. }
  56. }
  57. _handleMouseMove(event, target) {
  58. let point = target._windowToCanvas(event.clientX, event.clientY)
  59. let array = target.getTargets('mouse')
  60. if (array) {
  61. array.search(point)
  62. let selectedElements = array.selectedElements
  63. let unSelectedElements = array.unSelectedElements
  64. selectedElements.forEach(function(ele) {
  65. if (ele.hasListener('mousemove')) {
  66. let event = new Event(point.x, point.y, 'mousemove', ele)
  67. ele.emit('mousemove', event)
  68. }
  69. if (!ele.inBounds) {
  70. ele.inBounds = true
  71. if (ele.hasListener('mouseover')) {
  72. let event = new Event(point.x, point.y, 'mouseover', ele)
  73. ele.emit('mouseover', event)
  74. }
  75. }
  76. })
  77. unSelectedElements.forEach(function(ele) {
  78. if (ele.inBounds) {
  79. ele.inBounds = false
  80. if (ele.hasListener('mouseout')) {
  81. let event = new Event(point.x, point.y, 'mouseout', ele)
  82. ele.emit('mouseout', event)
  83. }
  84. }
  85. })
  86. }
  87. }
  88. _handleClick(event, target) {
  89. let point = target._windowToCanvas(event.clientX, event.clientY)
  90. let array = target.getTargets('click')
  91. if (array) {
  92. array.search(point)
  93. let selectedElements = array.selectedElements
  94. selectedElements.forEach(function(ele) {
  95. if (ele.hasListener('click')) {
  96. let event = new Event(point.x, point.y, 'click', ele)
  97. ele.emit('click', event)
  98. }
  99. })
  100. }
  101. }
  102. }

其中 SortArray 是模拟出的用来存放canvas同一事件绑定绘画对象的数组,方便调用

class SortArray {
  constructor() {
    this._data = []
    this.selectedElements = []
    this.unSelectedElements = []
  }

  add(ele) {
    if (!ele) return

    let i
    let data
    let index
    let result

    for (i = 0, index = 0; i < this._data.length; i++) {
      data = this._data[i]
      result = ele.compareTo(data)

      if (!result) return

      if (result > 0) {
        index++
      } else {
        break
      }
    }

    for (i = this._data.length; i > index; i--) {
      this._data[i] = this._data[i - 1]
    }

    this._data[index] = ele
  }

  contains(ele) {
    if (!ele) return false

    let low = 0
    let mid
    let high = this._data.length - 1

    while (low <= high) {
      mid = parseInt((low + high) / 2)

      if (this._data[mid] === ele) {
        return true
      }

      if (this._data[mid].compareTo(ele) < 0) {
        low = mid + 1
      } else {
        high = mid - 1
      }
    }

    return false
  }

  search(point) {
    let d
    this.selectedElements.length = 0
    this.unSelectedElements.length = 0

    for (let i = 0; i < this._data.length; i++) {
      d = this._data[i]
      if (d.comparePointX(point) > 0) {
        break
      }

      if (d.hasPoint(point)) {
        this.selectedElements.push(d)
      } else {
        this.unSelectedElements.push(d)
      }
    }
  }

  delete(ele) {
    let index = -1
    for (let i = 0; i < this._data.length; i++) {
      if (ele === this._data[i]) {
        index = i
        break
      }
    }
    this._data.splice(index, 1)
  }

  reset() {
    this._data.length = 0
    this.selectedElements.length = 0
    this.unSelectedElements.length = 0
  }
}

三、应用

启动canvas事件,调用事件总线的enableMove或enableClick方法给绑定的canvas绑定鼠标事件。