【问题标题】:How to make an image move on a custom path using JavaScript?如何使用 JavaScript 使图像在自定义路径上移动?
【发布时间】:2020-09-09 13:13:45
【问题描述】:

我想沿特定路径移动箭头。我知道我必须应用 CSS translate 来移动箭头,但我遇到了一个问题。

箭头需要向下移动,然后向左移动,然后向上移动,直到它从它开始的位置到达同一水平平原,但在其初始位置的左侧。

我可以把它往下移,这是第一步。但是如果我使用所有三种翻译方法,它会直接将其带到最终位置而不跟随路径。我尝试将三个 translate 方法及其转换放入单独的函数中,并在上一步结束时调用每个函数,但结果相同。

这是 HTML:

<div>
<img src="img/arwTest.png" alt="Click to rotate" id="arrow">
<img src="img/moveTest_2.png" alt="demonstration" id="demo">
<p>Click anywhere to move the arrow along the path.</p>
</div>

这是 CSS:

#demo, #arrow {
display: block;
margin: 0 auto;
}

#demo {
height: 300px;
}

#arrow {
height: 40px;
position: absolute;
left: 50%;
}

p {
text-align: center;
padding: 20px;
}

这是 JavaScript:

const arrow = document.getElementById("arrow");
arrow.style.transform = `rotate(90deg)`;

addEventListener('click', () => {
arrow.style.transform = `translate(0px,200px)`;
arrow.style.transition = `2s`;
})

Here's 整件事。

【问题讨论】:

标签: javascript html css dom css-transitions


【解决方案1】:

我相信您正在寻找 @keyframes css 声明和 animation css 属性:

@keyframes motion {
  0.000% { left: 30%; top: 70%; }
  33.33% { left: 70%; top: 70%; }
  66.66% { left: 50%; top: 30%; }
  100.0% { left: 30%; top: 70%; }
}

html, body {
  position: absolute;
  width: 100%; height: 100%;
  left: 0; top: 0;
  margin: 0; padding: 0;
}

.point {
  
  position: absolute;
  width: 20px; height: 20px;
  margin-left: -10px; margin-top: -10px;
  border-radius: 100%;
  background-color: #500000;
  
  animation: motion 2000ms infinite linear;
  
}
&lt;div class="point"&gt;&lt;/div&gt;

【讨论】:

  • 这太棒了。谢谢!
【解决方案2】:

一个新的 CSS 属性可以帮助您解决这个问题。

这是偏移路径。

在 sn-p 中查看它如何用于您请求的移动

悬停容器以激活它

另外,请注意,在堆栈溢出中,您需要发布代码示例。就算没用!

#container {
  width: 400px;
  height: 150px;
  border: dotted 5px black;
  margin: 30px;
   
}

#motion-demo {
  width: 40px;
  height: 40px;
  background: cyan;
  offset-path: path('M400 0 v 150 h -400 v -150');
   offset-distance: 0%;
   transition: offset-distance 2s;
 }


#container:hover #motion-demo {
    offset-distance: 100%;
}
<div id="container">
<div id="motion-demo"></div>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    • 2021-06-19
    • 1970-01-01
    • 2013-08-06
    • 1970-01-01
    • 2011-01-22
    • 1970-01-01
    相关资源
    最近更新 更多