Paranoidantroid Paranoidantroid - 3 months ago 25
CSS Question

Move browser with mouse

I am looking to try and do something like this where the content is off the screen and when you move the mouse the browser follows it around. I was thinking it would be similar to this where the edge of the screen animates when the mouse moves.

It looks like in the original example they use JS to change the

transform: matrix
. On the second link the screen is animated using greensock and the following code to change the CSS:

// Mouse move tilt effect
$(document).mousemove(function(event){

// Detect mouse position
var xPos = (event.clientX/$(window).width())-0.5;
var yPos = (event.clientY/$(window).height())-0.5;

// Tilt the hero container
TweenLite.to($hero, 0.6, {rotationY:5*xPos, rotationX:5*yPos, ease:Power1.easeOut, transformPerspective:900, transformOrigin:"center"});

// Update text on the page with the current mouse position
$(".bottom strong").text(event.pageX + ", " + event.pageY);
});


Is it possible to do something similar to do what I need?

Answer

Based on how I understood your intentions basically what you need to do is.

  1. Create a div container which has width and height greater than window size and fill it up with content
  2. Create div container which has width and height equal to window and overflow: hidden and contains the container in 1.
  3. Center container in 1 in 2 with transform: translateX(-25%) translateX(-25%); and transition: transform 1s;

After that

  1. Detected mouse position
  2. Calculate distance from center of window
  3. And based on that add or remove up to 25% to the translateX and translateY value

EDIT:

document.querySelector('body').style.transition = 'transform 1s';

window.addEventListener('mousemove', event => {
  const absMaxX = window.innerWidth / 2;
  const absMaxY = window.innerHeight / 2;

  const maxDistance = Math.sqrt(Math.pow(absMaxX, 2) + Math.pow(absMaxY, 2));

  const mouseX = event.clientX;
  const mouseY = event.clientY;

  const directionX = mouseX - absMaxX >= 0 ? 1 : -1;
  const directionY = mouseY - absMaxY >= 0 ? 1 : -1;

  const distance = Math.sqrt(Math.pow(mouseX - absMaxX, 2) + Math.pow(mouseY - absMaxY, 2))  
  const translation = distance / maxDistance * 100;

  document.querySelector('body').style.transform =
    `translateX(${directionX * translation}px) translateY(${directionY * translation}px)`
});
Comments