measuring angle of mouse movement
by Richard Hunter
HTML
<div class="container">
<div class="foo"></div>
</div>
<div id="bar"></div>
CSS
.container {
display: flex;
width: 90vw;
height: 50vh;
margin: 5vh 5vw;
background: antiquewhite;
}
.foo {
--angle: 270;
--background-width: 100%;
--background-height: 100%;
--background-position-y: 0%;
width: 100px;
height: 100px;
background: chocolate;
background-repeat: no-repeat;
margin: auto;
background-image: linear-gradient(calc(var(--angle) * 1deg), yellow 50%, crimson 51%);
background-position-x: 0%;
background-position-y: var(--background-position-y);
background-size: var(--background-width) var(--background-height);
}
JavaScript
const el = document.querySelector('.foo');
let gradient, angle, latch, counter;
let x1, x2, y1, y2;
function toDeg(rads) {
return rads * (180 / Math.PI);
}
el.addEventListener('mousemove', (event) => {
counter++;
if (counter > 3) {
if (!x2) {
x2 = event.clientX;
}
if (!y2) {
y2 = event.clientY;
}
if (!latch && x1 && x2 && y1 && y2) {
latch = true;
if (x1 === x2) {
if (y2 > y1) {
angle = 180;
} else {
angle = 0;
}
} else {
gradient = (y2 - y1) / (x2 - x1);
angle = toDeg(Math.atan(gradient));
if (x2 > x1) {
angle = 270 + toDeg(Math.atan(gradient));
} else if (x2 < x1) {
angle = 90 + toDeg(Math.atan(gradient));
}
}
el.style.setProperty('--angle', angle);
const height = 100 * ((1 / gradient) + 1);
const width = gradient * height;
el.style.setProperty('--background-height', height + '%');
el.style.setProperty('', width + '%');
}
}
});
el.addEventListener('mouseenter', (event) => {
x1 = event.clientX;
y1 = event.clientY;
counter = 0;
latch = false;
});