本文來做一個簡單的即時取得滑鼠座標的功能,在canvas動畫開發中,取得滑鼠的座標,鍵盤的按鍵等等,都是常用的操作,我們就慢慢得把他們封裝成一個公共庫。
一、事件的相容:
function bindEvent(obj, event, fn) { if (obj.attachEvent) { //ie obj.attachEvent('on' + event, function () { fn.call(obj); }); } else { //chrome&ff obj.addEventListener(event, fn, false); } }
上面相容ie8以及修正this關鍵字在ie低版本的指向,下方相容chrome和ff。其他更常用的封裝可以參考我的javascript開源框架gdom
二、用立即表達式搭建一個基本的庫
##添加獲取滑鼠座標的方法;(function (window) { window.G = {}; function bindEvent(obj, event, fn) { if (obj.attachEvent) { //ie obj.attachEvent('on' + event, function () { fn.call(obj); }); } else { //chrome&ff obj.addEventListener(event, fn, false); } } G.getPos = function( dom ){ var oPos = { x : 0, y : 0 }; bindEvent( dom, 'mousemove', function( ev ){ var oEvent = ev || event, x, y; if ( oEvent.pageX || oEvent.pageY ){ x = oEvent.pageX; y = oEvent.pageY; }else { x = oEvent.clientX + document.body.scrollLeft || document.documentElement.scrollLeft; y = oEvent.clientX + document.body.scrollTop || document.documentElement.scrollTop; } x -= dom.offsetLeft; y -= dom.offsetTop; oPos.x = x; oPos.y = y; } ); return oPos; }; })(window);
三、引入封裝的js庫,綁定canvas為監聽對象,列印目前滑鼠的座標
滑鼠的座標,我這裡畫了2根線,方便觀察.<script> ;(function (window) { window.G = {}; function bindEvent(obj, event, fn) { if (obj.attachEvent) { //ie obj.attachEvent(&#39;on&#39; + event, function () { fn.call(obj); }); } else { //chrome&ff obj.addEventListener(event, fn, false); } } G.getPos = function( dom ){ var oPos = { x : 0, y : 0 }; bindEvent( dom, 'mousemove', function( ev ){ var oEvent = ev || event, x, y; if ( oEvent.pageX || oEvent.pageY ){ x = oEvent.pageX; y = oEvent.pageY; }else { x = oEvent.clientX + document.body.scrollLeft || document.documentElement.scrollLeft; y = oEvent.clientX + document.body.scrollTop || document.documentElement.scrollTop; } x -= dom.offsetLeft; y -= dom.offsetTop; oPos.x = x; oPos.y = y; } ); return oPos; }; })(window); </script> <script> window.onload = function(){ var oCanvas = document.querySelector( "#canvas" ), oGc = oCanvas.getContext( '2d' ), width = oCanvas.width, height = oCanvas.height, oInfo = document.querySelector( "#info" ), oPos = G.getPos( oCanvas ); oCanvas.addEventListener( "mousemove", function(){ oGc.clearRect( 0, 0, width, height ); oGc.beginPath(); oGc.moveTo( oPos.x, 0 ); oGc.lineTo( oPos.x, height ); oGc.moveTo( 0, oPos.y ); oGc.lineTo( width, oPos.y ); oGc.closePath(); oGc.strokeStyle = '#09f'; oGc.stroke(); oInfo.innerHTML = '鼠标的当前坐标是:(' + oPos.x + ',' + oPos.y + ')'; }, false ); } </script>
以上是如何即時取得滑鼠的當前座標的詳細內容。更多資訊請關注PHP中文網其他相關文章!