JSFiddle - React, Tailwind, and code Playground
by Tan
HTML
<div id="container">
<div id="inner">
<div class="demo-img">
<div class="demo-overlay">
</div>
</div>
</div>
</div>
CSS
body {
width: 100%;
min-height: 100vh;
margin: 0;
display: flex;
justify-content: center;
align-items: center;
background-color: rgb(223, 223, 223);
}
#container {
perspective: 30px;
}
#inner {
transition: transform 0.5s;
-webkit-transition: transform 0.5s;
box-shadow: 2px 2px 50px rgba(0, 0, 0, 0.2);
}
/*============================================================
* EXTRAS
*============================================================*/
.demo-img {
/* Photo by David Marcu on Unsplash */
border: solid white 15px;
background-image: url("https://images.unsplash.com/photo-1469474968028-56623f02e42e?auto=format&fit=crop&w=1953&q=80");
background-size: cover;
background-repeat: no-repeat;
}
#container:hover .demo-overlay {
opacity: 1;
}
#container:hover {
cursor: pointer;
}
.demo-overlay {
width: 25em;
padding: 10em 0;
opacity: 0;
background-color: rgba(0, 0, 0, 0.5);
transition: opacity 0.4s;
}
.demo-overlay svg {
display: block;
margin: 0 auto;
fill: white;
}
JavaScript
(function() {
// Init
var container = document.getElementById("container"),
inner = document.getElementById("inner");
// Mouse
var mouse = {
_x: 0,
_y: 0,
x: 0,
y: 0,
updatePosition: function(event) {
var e = event || window.event;
this.x = e.clientX - this._x;
this.y = (e.clientY - this._y) * -1;
},
setOrigin: function(e) {
this._x = e.offsetLeft + Math.floor(e.offsetWidth / 2);
this._y = e.offsetTop + Math.floor(e.offsetHeight / 2);
},
show: function() {
return "(" + this.x + ", " + this.y + ")";
}
};
// Track the mouse position relative to the center of the container.
mouse.setOrigin(container);
//----------------------------------------------------
var counter = 0;
var refreshRate = 10;
var isTimeToUpdate = function() {
return counter++ % refreshRate === 0;
};
//----------------------------------------------------
var onMouseEnterHandler = function(event) {
update(event);
};
var onMouseLeaveHandler = function() {
inner.style = "";
};
var onMouseMoveHandler = function(event) {
if (isTimeToUpdate()) {
update(event);
}
};
//----------------------------------------------------
var update = function(event) {
mouse.updatePosition(event);
updateTransformStyle(
(mouse.y / inner.offsetHeight / 2).toFixed(2),
(mouse.x / inner.offsetWidth / 2).toFixed(2)
);
};
var updateTransformStyle = function(x, y) {
var style = "rotateX(" + x + "deg) rotateY(" + y + "deg)";
inner.style.transform = style;
inner.style.webkitTransform = style;
inner.style.mozTranform = style;
inner.style.msTransform = style;
inner.style.oTransform = style;
};
//--------------------------------------------------------
container.onmousemove = onMouseMoveHandler;
container.onmouseleave = onMouseLeaveHandler;
container.onmouseenter = onMouseEnterHandler;
})();