var playerCount = 0;
var imgCount = 0;
/*
* @description:计算鼠标的方向
* @param:浏览器属性,元素
* @author:aleck
* @create:2021/08/25
*
* */
function XYZ(e,player):Number{
var w = player.offsetWidth,
h = player.offsetHeight,
toTop = player.getBoundingClientRect().top + document.body.scrollTop, //兼容滚动条
x = (e.pageX - player.getBoundingClientRect().left - (w / 2)) * (w > h ? (h / w) : 1), //获取当前鼠标的x轴位置
y = (e.pageY - toTop - h/2) * (h > w ? (w / h) : 1),
//上面对长方形也做了兼容,也就是按照最小的那个边的一半作为半径了
//例如有一个宽6,高是2的矩形 右上角的坐标就是{x:3,y:1},经过上面的计算后{x:2/6 * 3,y:1}=》{x:1,y:1}
// 算出来也就是45°的样子
//如果是正方形,可以去掉后面的系数(w>h && h>w)
//direction的值为“0,1,2,3”分别对应着“上,右,下,左”
direction = Math.round((((Math.atan2(y, x) * 180 / Math.PI) + 180) / 90) + 3) % 4;
//eventType = e.type,//
// res = Math.atan2(y, x) / (Math.PI / 180) + 180 ,//试试其他的计算
// console.log(((Math.atan2(y, x) * 180 / Math.PI) + 180));
// console.log(Math.round((Math.atan2(y, x) / (Math.PI / 180) + 180) / 90 + 3) % 4);
//dirName = new Array('上方','右侧','下方','左侧');
//dirName[direction]
return direction;
}
document.onmousemove = mouseMove;
function mouseMove(ev)
{
var player = document.getElementById("player");
var img = document.getElementById("img");
Ev= ev || window.event;
var res = XYZ(ev,player);
console.log(res);
if(ev.toElement.id=="player" || ev.toElement.id=="img"){
//“0,1,2,3”分别对应着“上,右,下,左”
switch (res){
case 0:
//上
playerCount -= 0.01;
imgCount -= 0.01;
if(playerCount>1 || imgCount>1){
playerCount -= 0.1;
imgCount -= 0.01;
}
break;
case 1:
//右
playerCount += 0.1;
imgCount += 0.01;
break;
case 2:
//下
playerCount -= 0.01;
imgCount -= 0.01;
if(playerCount>1 || imgCount>1){
playerCount -= 0.1;
imgCount -= 0.01;
}
break;
case 3:
//左
playerCount -= 0.01;
imgCount -= 0.01;
if(playerCount>1 || imgCount>1){
playerCount -= 0.1;
imgCount -= 0.01;
}
break;
}
player.style.transform = " scale(1) translate("+ playerCount +"px, 0px) rotate(0deg)";
img.style.transform = " scale(1) translate("+ imgCount +"px, 0px) rotate(0deg)";
}
}