【问题标题】:How to make a move animation which can move an image from current place to where the user clicks如何制作移动动画,可以将图像从当前位置移动到用户单击的位置
【发布时间】:2022-01-10 23:00:37
【问题描述】:

我有一张图片,我想将图片从其当前位置(最初放置的位置)移动到另一个位置用户点击次数。我的意思是,当用户单击 Html 页面中的任何位置时,图像应该移动到那里,我需要将其设为移动动画,以便图像应在 3 秒内从当前位置移动到另一个位置(例如)。我怎样才能做到这一点? vanilla JavaScriptjQuery 可以帮忙吗?无论如何我只想制作这个动画,但React 在我的笔记本电脑上无法有效工作,所以请在jQueryplain JavaScript 中回答。

在我的html页面中:

<img src="./wolf.png" alt="wolf" style="width:3%;" id="wolf">

在我的 css 文件中:

#wolf {
animation-name: move;
animation-duration: 3s;
animation-fill-mode: forwards;
}
@keyframes move {
/*
Need help
*/
}

在 .js 文件中:

$(document).ready(function() {
// Need help
})

【问题讨论】:

  • 您应该重新考虑“需要 3 秒”的规则。如果您的页面很长(例如 300 000 像素)或点击距离只有 3 像素,该怎么办。 3 秒内 3 个像素非常慢,3 秒内 300 000 个像素非常快。
  • @flowtron 如果您知道如何根据距离更改时间,请编辑您的答案,我将不胜感激。感谢您的关注。
  • 这完全取决于您想要/需要的速度、持续时间或其他限制 - 我已经实施了一种方法。

标签: javascript jquery css animation


【解决方案1】:

要找出鼠标光标在用户点击的位置,您可以使用

    document.onclick= function(event) {
    pointerX = event.pageX;
    pointerY = event.pageY;
}
    console.log('Cursor at: '+pointerX+', '+pointerY);

您可以将此与 element.style.translate 中的翻译结合起来,并将元素从当前位置移动到用户点击的位置。

【讨论】:

    【解决方案2】:

    https://developer.mozilla.org/en-US/docs/Web/API/Web_Animations_API/Using_the_Web_Animations_API 上,我们了解到 DOM 元素具有 animate 方法。

    var dX = 150, dY = 50; // TODO: proper distance between current and target location
    document.getElementById("wolf").animate(
      [
        { transform: `translate(${dX}px, ${dY}py)` },
      ], {
        duration: 3000 // should be linked to distance - 3px in 3s is **SLOW**
      }
    );
    

    要使持续时间取决于距离,您需要指定这三秒(或其他任何时间)的距离,然后计算行驶距离。毕达哥拉斯向我们展示了如何。 这是一个 jsfiddle 可以完成所有这些 - 享受:https://jsfiddle.net/flowtron/0qkuvtd7/

    核心有以下计算:

    // once on pageload:
    screendiagonal = Math.sqrt( screen.width * screen.width + screen.height * screen.height ); // Pythagoras
    // every move - what are the X and Y distances to travel?
    let delta = { x: targetCoord.x - pos.x, y: targetCoord.y - pos.y };
    let curdur = ( Math.sqrt(delta.x*delta.x+delta.y*delta.y) / screendiagonal ) * 3000; // Pythagoras - travel distance in time relative to screendiagonal
    

    这样屏幕的对角线就需要三秒钟。

    【讨论】:

      猜你喜欢
      • 2013-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-09
      • 2015-05-09
      相关资源
      最近更新 更多