最近在研究web中元素的方位問題,判斷進(jìn)入一個元素是方向遇到另一個問題atan2(y,x)的使用鹏倘。
這么多年沒有關(guān)注三角函數(shù)了,好多都已經(jīng)忘了。
Javascript 中定義:atan2() 方法可返回從 x 軸到點(diǎn) (x,y) 之間的角度旋圆,這個角度就是(-π,π)麸恍。
javascript代碼實(shí)現(xiàn):
console.log(Math.atan2(20,10)); //坐標(biāo)(10灵巧,20)的弧度?
onsole.log(Math.atan2(10,10)); //坐標(biāo)(10,10)的弧度
onsole.log(Math.atan2(-10,10)); //坐標(biāo)(10抹沪,-10)的弧度
onsole.log(Math.atan2(-10,-10)); //坐標(biāo)(-10刻肄,-10)的弧度
onsole.log(Math.atan2(10,-10)); //坐標(biāo)(-10,10)的弧度
頁面中一個矩形盒子獲取鼠標(biāo)進(jìn)入盒子的方向
/**
* [getDirection 獲取鼠標(biāo)進(jìn)入盒子的方向]
* @param? {[type]} ev? [事件]
* @param? {[type]} obj [盒子對象]
* @return {[type]}? ? [description]
*
* 函數(shù)中 x,y軸的(0,0)在內(nèi)容盒子的中心
*
*/
var getDirection = function(ev, obj) {
? ? ? ? ? ? var w = obj.offsetWidth,
? ? ? ? ? ? ? ? ? h = obj.offsetHeight,
? ? ? ? ? ? ? ? ? x = (ev.pageX - obj.offsetLeft - (w / 2) * (w > h ? (h / w) : 1)),
? ? ? ? ? ? ? ? ?y = (ev.pageY - obj.offsetTop - (h / 2) * (h > w ? (w / h) : 1)),
? ? ? ? ? ? ? ? d = Math.round(Math.atan2(y, x) / 1.57079633 + 5) % 4;
? ? ? ? ? ? ? ? console.log('atan2:' + Math.atan2(y, x) / 1.57079633 + 5)
? ? ? ? ? ? ? ?console.log('w:' + w, 'h:' + h, 'x:' + x, 'y:' + y, 'd:' + d)
? ? ? ? ? ? ? ?return d;
};
var addContent = function(ev, obj, state) {
? ? ? ? ? ? ? ? ?var direction = getDirection(ev, obj);
? ? ? ? ? ? ? ? ?switch(direction) {
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?case 0: ??
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? obj.innerHTML ='top'; break;
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?case 1:
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? obj.innerHTML='right'; break;
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?case 2:
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?obj.innerHTML ='bottom'; break;
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?case 3:
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?obj.innerHTML ='left'; break;
? ? ? ? ? ? ? ? ? }
};
// bind events
document.getElementById('con').addEventListener('mouseover', function(ev) {
? ? ? ? ? ? ? ? addContent(ev, this, 'in');
}, false);
document.getElementById('con').addEventListener('mouseout', function(ev) { ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? addContent(ev, this, 'out');
}, false);
其實(shí)判斷盒子從那個方位進(jìn)入盒子有很多方法:
坐標(biāo)軸系X,Y坐標(biāo)判斷
以盒子的右下角為原點(diǎn)
x>0 && y>0 && x<y ? ?(top)
x>0 && y>0 && x>y ? ?(right)
x>=0 && y==0 ? ?(bottom)
x==0 && y>0 ? ?(left)