前言
canvas 沒有提供為其內部元素添加事件監聽的方法,因此如果要使 canvas 內的元素能夠響應事件,需要自己動手實現。實現方法也很簡單,首先獲得鼠標在 canvas 上的坐標,計算當前坐標在哪些元素內部,然后對元素進行相應的操作。配合自定義事件,我們就可以實現為 canvas 內的元素添加事件監聽的效果。
自定義事件
為了實現javascript對象的自定義事件,我們可以創建一個管理事件的對象,該對象中包含一個內部對象(當作map使用,事件名作為屬性名,事件處理函數作為屬性值,因為可能有個多個事件處理函數,所以使用數組存儲事件處理函數),存儲相關的事件。然后提供一個激發事件的函數,通過使用 call
方法來調用之前綁定的函數。下面是代碼示例:
(function () { cce.EventTarget = function () { this._listeners = {}; this.inBounds = false; }; cce.EventTarget.prototype = { constructor: cce.EventTarget, // 查看某個事件是否有監聽 hasListener: function (type) { if (this._listeners.hasOwnProperty(type)) { return true; } else { return false; } }, // 為事件添加監聽函數 addListener: function (type, listener) { if (!this._listeners.hasOwnProperty(type)) { this._listeners[type] = []; } this._listeners[type].push(listener); cce.EventManager.addTarget(type, this); }, // 觸發事件 fire: function (type, event) { if (event == null || event.type == null) { return; } if (this._listeners[event.type] instanceof Array) { var listeners = this._listeners[event.type]; for (var i = 0, len = listeners.length; i < len; i++) { listeners[i].call(this, event); } } }, // 如果listener 為null,則清除當前事件下的全部事件監聽 removeListener: function (type, listener) { if (listener == null) { if (this._listeners.hasOwnProperty(type)) { this._listeners[type] = []; cce.EventManager.removeTarget(type, this); } } if (this._listeners[type] instanceof Array) { var listeners = this._listeners[type]; for (var i = 0, len = listeners.length; i