用户交互
element.addEventListener(event, function, useCapture);
element.removeEventListener(event, function, useCapture);
window.tool={}; window.tool.captureMousePoint=function(element){ var mousePoint={x:0,y:0}; element.addEventListener("mousemove",function(event){ var event=event || window.event; var x=0,y=0; if(event.pageX || event.pageY){ x=event.pageX; y=event.pageY; }else{ x = event.clientX + document.body.scrollLeft +document.documentElement.scrollLeft; y = event.clientY + document.body.scrollTop +document.documentElement.scrollTop; } x -= element.offsetLeft; y -= element.offsetTop; mousePoint.x = x; mousePoint.y = y; },false); return mousePoint; };
var aa=tool.captureMousePoint(cc); document.getElementById("canvas").addEventListener("mousedown",function(){ console.log(aa); });
三、键盘事件
键盘事件有两个:
keydown
keyup
我们将键盘事件绑定到window上:
window.tool.captureMoveDirection=function(event){ var event=event || window.event; var direction=null; switch (event.keyCode) { case 38: direction="up"; break; case 40: direction="down"; break; case 37: direction="left"; break; case 39: direction="right"; break; default: direction=null; } return direction; }
调用:
window.addEventListener('keydown', function(event){ var direction=tool.captureMoveDirection(event); console.log(direction); }, false);
四、触摸事件
触摸事件包括以下3种:
touchstart
touchend
touchmove
window.tool.captureTouchPoint = function(element) { var touchPoint = { x: null, y: null, isPressed: false, event: null }; // 绑定touchstart事件 element.addEventListener('touchstart', function(event) { touchPoint.isPressed = true; touchPoint.event = event; }, false); // 绑定touchend事件 element.addEventListener('touchend', function(event) { touchPoint.isPressed = false; touchPoint.x = null; touchPoint.y = null; touchPoint.event = event; }, false); //绑定touchmove事件 element.addEventListener('touchmove', function(event) { var x, y, touch_event = event.touches[0]; //第一次touch if (touch_event.pageX || touch_event.pageY) { x = touch_event.pageX; y = touch_event.pageY; } else { x = touch_event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft; y = touch_event.clientY + document.body.scrollTop + document.documentElement.scrollTop; } //减去偏移量 x -= offsetLeft; y -= offsetTop; touchPoint.x = x; touchPoint.y = y; touchPoint.event =touch_event; }, false); //返回touch对象 return touchPoint; }