gpt4 book ai didi

javascript - 通过 svg 路径滚动移动图像

转载 作者:行者123 更新时间:2023-12-01 06:32:52 25 4
gpt4 key购买 nike

我想通过滚动上的 svg 路径移动对象=) 我试图将滚动上的部分路径添加到路径中,但它仍然不起作用。救命!!!=) https://jsfiddle.net/YuriiBielozertsev/Ltx9ed0L/

<?xml version="1.0"?>
<svg viewBox="0 0 120 120" xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink">
<!-- Draw the outline of the motion path in grey, along with 2 small circles at key points -->
<path d="M10,110 A120,120 -45 0,1 110 10 A120,120 -45 0,1 10,110" stroke="green" stroke-width="2" fill="none" id="theMotionPath"/>
<circle cx="10" cy="110" r="3" fill="#000"/>
<circle cx="110" cy="10" r="3" fill="#000"/>

<!-- Red circle which will be moved along the motion path. -->
<circle cx="0" cy="" r="5" fill="red">

<!-- Define the motion path animation -->
<animateMotion dur="6s" repeatCount="indefinite">
<mpath xlink:href="#theMotionPath"/>
</animateMotion>
</circle>
</svg>

最佳答案

类似这样的吗?

这是如何工作的:

  1. 当我们收到滚动事件时,我们:
  2. 计算我们距离页面有多远
  3. 使用 <path> 将此百分比转换为路径上的位置元素函数getTotalLength()getPointAtLength() .
  4. 重新定位该点,使其出现在此时。

function positionTheDot() {

// What percentage down the page are we?
var scrollPercentage = (document.documentElement.scrollTop + document.body.scrollTop) / (document.documentElement.scrollHeight - document.documentElement.clientHeight);

// Get path length
var path = document.getElementById("theMotionPath");
var pathLen = path.getTotalLength();

// Get the position of a point at <scrollPercentage> along the path.
var pt = path.getPointAtLength(scrollPercentage * pathLen);

// Position the red dot at this point
var dot = document.getElementById("dot");
dot.setAttribute("transform", "translate("+ pt.x + "," + pt.y + ")");

};

// Update dot position when we get a scroll event.
window.addEventListener("scroll", positionTheDot);

// Set the initial position of the dot.
positionTheDot();
.verylong {
height: 2000px;
}

svg {
position: fixed;
width: 200px;
height: 200px;
}
<svg viewBox="0 0 120 120" xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink">
<!-- Draw the outline of the motion path in grey, along with 2 small circles at key points -->
<path d="M10,110 A120,120 -45 0,1 110 10 A120,120 -45 0,1 10,110" stroke="green" stroke-width="2" fill="none" id="theMotionPath"/>
<circle cx="10" cy="110" r="3" fill="#000"/>
<circle cx="110" cy="10" r="3" fill="#000"/>

<!-- Red circle which will be moved along the motion path. -->
<circle cx="0" cy="0" r="5" fill="red" id="dot"/>
</svg>

<div class="verylong">
</div>

关于javascript - 通过 svg 路径滚动移动图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40608999/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com