48 lines
1.4 KiB
JavaScript
48 lines
1.4 KiB
JavaScript
export class CardTilter {
|
|
|
|
/**
|
|
*
|
|
* @param card Card to be moved
|
|
* @param tilt max tilting angle in degree
|
|
* @param perspective perspective in pixels
|
|
*/
|
|
constructor({card : card, tilt : tilt, perspective : perspective}) {
|
|
this.card = card;
|
|
this.tilt = tilt;
|
|
this.perspective = perspective;
|
|
this.watch()
|
|
}
|
|
|
|
watch(){
|
|
this.card.addEventListener('mousemove', (e) => {
|
|
const rotations = this.calculatePositions(e.clientX, e.clientY);
|
|
this.transform(rotations.x, rotations.y);
|
|
});
|
|
|
|
this.card.addEventListener('mouseleave', () => {
|
|
this.reset();
|
|
});
|
|
}
|
|
|
|
calculatePositions(cursorX, cursorY) {
|
|
const rect = this.card.getBoundingClientRect();
|
|
const x = cursorX - rect.left;
|
|
const y = cursorY - rect.top;
|
|
|
|
const percentX = (x / rect.width) - 0.5;
|
|
const percentY = (y / rect.height) - 0.5;
|
|
|
|
const rotateX = -percentY * this.tilt;
|
|
const rotateY = percentX * this.tilt;
|
|
|
|
return {x : rotateX, y : rotateY};
|
|
};
|
|
|
|
transform(rotationX, rotationY) {
|
|
this.card.style.transform = `translateY(-10px) perspective(${this.perspective}px) rotateX(${rotationX}deg) rotateY(${rotationY}deg) scale(1.05)`;
|
|
}
|
|
|
|
reset(){
|
|
this.card.style.transform = `rotateX(0deg) rotateY(0deg) scale(1)`;
|
|
}
|
|
} |