【问题标题】:Slightly move img accordingly with mousemove用 mousemove 稍微移动 img
【发布时间】:2020-12-07 00:08:36
【问题描述】:

我正在尝试达到以下效果:https://github.com/thispagedoesntexist(角色拥有的那个)

我希望我的图像根据我移动鼠标的位置稍微移动。也许它与 3d 转换和缩放有关......我不知道

我浏览了网络并试图自己想出一些东西,但我做不到。这是我停止的地方:

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)`;
});

谢谢

【问题讨论】:

  • 您发布的链接已损坏。
  • @MohammadOsama 这就是重点 ;) 在 404 消息周围移动鼠标
  • @MohammadOsama 什么

标签: javascript mousemove


【解决方案1】:

你在正确的轨道上。要实现这种视差效果,您可以对元素应用不同的比率。困难的部分是找到/创建正确的图像并找到正确的比例,使其看起来有点“逼真”:

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" />

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-12
    • 1970-01-01
    • 2020-06-29
    • 2014-05-03
    • 1970-01-01
    • 1970-01-01
    • 2021-01-29
    相关资源
    最近更新 更多