JSFiddle - React, Tailwind, and code Playground
HTML
<div id="test"></div>
CSS
#test{
position: fixed;
width: 100px;
height: 100px;
top: 0px;
right: 0px;
background: red;
}
JavaScript
(function() {
document.onmousemove = handleMouseMove;
})();
//https://stackoverflow.com/questions/7790725/javascript-track-mouse-position
function handleMouseMove(event) {
var eventDoc, doc, body;
event = event || window.event;
if (event.pageX == null && event.clientX != null) {
eventDoc = (event.target && event.target.ownerDocument) || document;
doc = eventDoc.documentElement;
body = eventDoc.body;
event.pageX = event.clientX +
(doc && doc.scrollLeft || body && body.scrollLeft || 0) -
(doc && doc.clientLeft || body && body.clientLeft || 0);
event.pageY = event.clientY +
(doc && doc.scrollTop || body && body.scrollTop || 0) -
(doc && doc.clientTop || body && body.clientTop || 0 );
}
// Use event.pageX / event.pageY here
document.getElementById("test").style.opacity = scale(event.pageX, 0, 500, 1, 0);
document.getElementById("test").style.transform = `rotate(${scale(event.pageY, 0, 200, 0, 90)}deg)`;
}
const scale = (value, inMin, inMax, outMin, outMax) => {
if (value < inMin) {
return outMin;
}
if(value > inMax){
return outMax;
}
let scaled = (value - inMin) * (outMax - outMin) / (inMax - inMin) + outMin;
return scaled;
}