const DEG_TO_RAD = Math.PI / 180;
const RAD_TO_DEG = 180 / Math.PI;
const point = ( x = 0, y = 0 ) => ({ x, y });
const length = ( { x, y } ) => Math.sqrt( x * x + y * y );
const normalize = ( vector ) => {
let vectorLength = length( vector );
let { x, y } = vector;
return point( x / vectorLength, y / vectorLength );
};
const subtract = ( a, b ) => ({ x: a.x - b.x, y: a.y - b.y });
const DIRECTIONS = {
TOP: "top",
RIGHT: "right",
BOTTOM: "bottom",
LEFT: "left"
};
const defaultBorder = `3px solid black`;
const getBorder = side => ({
borderTop: `${ side === DIRECTIONS.TOP ? defaultBorder : '' }`,
borderRight: `${ side === DIRECTIONS.RIGHT ? defaultBorder : '' }`,
borderBottom: `${ side === DIRECTIONS.BOTTOM ? defaultBorder : '' }`,
borderLeft: `${ side === DIRECTIONS.LEFT ? defaultBorder : '' }`,
})
const actionMap = {
[ DIRECTIONS.TOP ]: element => Object.assign( element.style, getBorder( DIRECTIONS.TOP ) ),
[ DIRECTIONS.RIGHT ]: element => Object.assign( element.style, getBorder( DIRECTIONS.RIGHT ) ),
[ DIRECTIONS.BOTTOM ]: element => Object.assign( element.style, getBorder( DIRECTIONS.BOTTOM ) ),
[ DIRECTIONS.LEFT ]: element => Object.assign( element.style, getBorder( DIRECTIONS.LEFT ) ),
}
let rect = document.body.querySelector('.rect');
let rectangle = rect.getBoundingClientRect();
let center = point(
rectangle.width / 2 + rectangle.left,
rectangle.height / 2 + rectangle.top
);
document.addEventListener('mousemove', document_mouseMoveHandler);
function document_mouseMoveHandler( { clientX, clientY } ){
let mouse = point( clientX, clientY );
let mc = subtract( mouse, center );
let direction = normalize( mc );
let angle = Math.atan2( direction.y, direction.x ) * RAD_TO_DEG;
let type = getDirection( angle );
let action = actionMap[ type ];
action( rect );
}
function getDirection( angle ){
if( angle <= -45 && angle > -130 ){
return DIRECTIONS.TOP;
}else if( angle > -180 && angle <= -130 || angle <= 180 && angle > 130 ){
return DIRECTIONS.LEFT;
}else if( angle > 45 && angle <= 130 ){
return DIRECTIONS.BOTTOM;
}else if( angle <= 45 && angle > -45 ){
return DIRECTIONS.RIGHT;
}
}
Для наглядности
/* css */
.rect {
width: 100px;
height: 100px;
background: tomato;
position: absolute;
top: 50%;
left: 50%;
transform: translate( -50%, -50% );
}
<div class="rect"></div>