Liana Pavlicheva
Liana Pavlicheva

Reputation: 127

Slightly move img accordingly with mousemove

I am trying to achieve the following effect: https://github.com/thispagedoesntexist (the one that the character has)

I want my image to move just slightly according to where I move my mouse. Maybe it has something to do with 3d transformation and scaling ... I don't know

I browsed the web and tried to come up with something by myself, but I couldn't. Here's where I stpoped:

HTML

<img class="image" id="module-hotjar" src="./img/image.png" alt="">

CSS

.image{
    position: fixed;
    z-index: 1;
    display: flex;
    bottom: -300px;
    height: 90vh;
    left: 15%;
    transition: 0.3s ease;
    transform: translate(0px, 0px);
}

JS

var image = document.querySelector('.image');
let root = document.documentElement;

root.addEventListener('mousemove', (e) => {
;
  x = e.offsetX / 10;
  y = e.offsetY / 10;
  image.style.transform = `translate(${x}px,${y}px)`;
});

Thank you

Upvotes: 0

Views: 909

Answers (1)

blex
blex

Reputation: 25634

You're on the right track. To achieve this parallax effect, you can apply different ratios to the elements. The difficult part is finding/creating the right images and finding the correct ratios, so that it looks kind of "realistic":

const background = document.querySelector('.background'),
      patrick = document.querySelector('.patrick'),
      bob = document.querySelector('.bob'),
      root = document.documentElement;

root.addEventListener('mousemove', (e) => {
  const x = e.clientX,
        y = e.clientY;
  background.style.transform = `translate(${-x / 20}px,${-y / 40}px)`;
  patrick.style.transform = `translate(${-x / 15}px,${-y / 40}px)`;
  bob.style.transform = `translate(${x / 10}px,${y / 10}px)`;
});
.background{
    position: fixed;
    bottom: -5vh;
    width: 110vw;
    left: -5vw;
}
.patrick{
    position: fixed;
    bottom: -7vh;
    height: 90vh;
    right: 10%;
    margin-left: -25%;
}
.bob{
    position: fixed;
    bottom: -10vh;
    height: 90vh;
    left: 50%;
    margin-left: -25%;
}
<img class="background" src="https://wallpaperaccess.com/full/3896911.jpg" />
<img class="patrick" src="https://assets.stickpng.com/thumbs/5cb78e9b7ff3656569c8cec1.png" />
<img class="bob" src="https://lh3.googleusercontent.com/proxy/wHCNlCMGLIi4Fa3QQlxyLRw_uyZoLauUFpMCDzSowxbjmA6gy12KqK6Fe6XD45T6EWas1dimdsh7Rfl3Mv9w3Z28iJAKCqaQLu8TChGV8yzbRqL7WpwHozSPaDYBJIefwmayIaROJ7M" />

Upvotes: 3

Related Questions