【问题标题】:Reduce speed of following image降低跟随图像的速度
【发布时间】:2021-12-31 09:10:59
【问题描述】:

我正在制作一个 gif 跟随光标的游戏。有什么办法可以降低速度,使跟随光标的图像以比光标本身恒定(但更慢)的速度移动?

基本上现在我分配的 gif 正在充当链接替换光标。我希望 gif 以自己的速度跟随并追上光标。

谢谢

<script>
document.querySelector(".testsite").onmousemove = (e) => {
  const x = e.pageX - e.target.offsetLeft;
  const y = e.pageY - e.target.offsetTop;
 
  e.target.style.setProperty("--x", `${x}px`);
  e.target.style.setProperty("--y", `${y}px`);
};
 
</script>
<style>
body {
  justify-content: center;
  align-items: center;
  min-height: 100vh;
}
 
.testsite {
/* container */
  width: 500px;
  height: 500px;
  position: relative;
  appearance: none;
  background: grey;
  padding: 10px 20px;
  border: none;
  color: white;
  font-size: 1.2em;
  cursor: none;
  outline: none;
  overflow: hidden;
  border-radius: 10px;
  box-shadow: black;
}
.testsite span {
  position: relative;
  pointer-events: none;
}
.testsite::before {
  --size: 0;
  content: "";
  position: absolute;
  left: var(--x);
  top: var(--y);
  width: 32px;
  height: 32px;
  background-image: url("html5.gif");
  animation-duration: 1s;

  transform: translate(-50%, -50%);
}

</style>
<html>
<body>
<div class="testsite">
  
</div>
</body>
</html>

【问题讨论】:

    标签: javascript html jquery css


    【解决方案1】:

    您可以将 js 的 x 和 y 坐标操作变成一个函数,然后在该函数中添加一个 setTimeout 以每 100 毫秒运行一次,或者您希望延迟多长时间。在这里查看,注意我还从.testsite 中删除了pointer:none;

    document.querySelector(".testsite").onmousemove = (e) => {
      const x = e.pageX - e.target.offsetLeft;
      const y = e.pageY - e.target.offsetTop;
      
      function runInt() {
      e.target.style.setProperty("--x", `${x}px`);
      e.target.style.setProperty("--y", `${y}px`);
      }
     setTimeout(runInt, 100);
    };
    body {
      justify-content: center;
      align-items: center;
      min-height: 100vh;
    }
     
    .testsite {
    /* container */
      width: 500px;
      height: 500px;
      position: relative;
      appearance: none;
      background: grey;
      padding: 10px 20px;
      border: none;
      color: white;
      font-size: 1.2em;
    
      outline: none;
      overflow: hidden;
      border-radius: 10px;
      box-shadow: black;
    }
    .testsite span {
      position: relative;
      pointer-events: none;
    }
    .testsite::before {
      --size: 0;
      content: "";
      position: absolute;
      left: var(--x);
      top: var(--y);
      width: 32px;
      height: 32px;
      background-image: url("https://www.springbrookanimalcarecenter.com/blog/wp-content/uploads/2017/10/Springbrook_iStock-612247460-150x150.jpg");
      animation-duration: 1s;
      transform: translate(-50%, -50%);
    }
    <html>
    <body>
    <div class="testsite">
    </div>
    </body>
    </html>

    【讨论】:

      猜你喜欢
      • 2022-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-25
      • 2022-09-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多