javascript - JavaScript 在 Scroll 上沿 SVG 路径移动 gif 不起作用
问题描述
我想在滚动时沿 svg 路径移动动画 gif,我一直在尝试调整沿 SVG 移动的文本,<textPath>
但它不起作用。我想知道最好的解决方案是什么。
<svg id="text-container" viewBox="0 0 1000 194" xmlns="http://www.w3.org/2000/svg">
<path id="text-curve" d="M0 100s269.931 86.612 520 0c250.069-86.612 480 0 480 0" fill="none"/>
<text y="40" font-size="2.1em">
<textPath id="text-path" href="#text-curve">
<img src="../imagesIndex/originals/dragon.gif" height="194px"/>
</textPath>
</text>
</svg>
我可以让文本沿着 SVG 曲线移动,但不能让图像移动。我尝试过扩展 SVG 视图框,使用上面定义的高度缩小图像,我尝试将 SVG 更改<textPath
为<path
它不起作用。我无处可去。
图像出现,但它不会沿着 SVG 的路径移动。
这是Javascript
<script>
console.clear();
var textPath = document.querySelector('#text-path');
var textContainer = document.querySelector('#text-container');
var path = document.querySelector( textPath.getAttribute('href') );
var pathLength = path.getTotalLength();
console.log(pathLength);
function updateTextPathOffset(offset){
textPath.setAttribute('startOffset', offset);
}
updateTextPathOffset(pathLength);
function onScroll(){
requestAnimationFrame(function(){
var rect = textContainer.getBoundingClientRect();
var scrollPercent = rect.y / window.innerHeight;
console.log(scrollPercent);
updateTextPathOffset( scrollPercent * 2 * pathLength );
});
}
window.addEventListener('scroll',onScroll);
</script>
抱歉,如果这个问题是重复的。我确实有一个 Greensock GSAP、ShockinglyGreen 订阅、所有可用的库,但我还没有深入研究它。
解决方案
下面是一些示例代码,用于将 SVG<image>
元素定位在沿由页面滚动确定的路径的位置。
var path = document.querySelector('#text-curve');
var cat = document.querySelector('#cat');
var catWidth = 40;
var catHeight = 40;
function updateImagePosition(offset) {
let pt = path.getPointAtLength(offset * path.getTotalLength());
cat.setAttribute("x", pt.x - catWidth/2);
cat.setAttribute("y", pt.y - catHeight/2);
}
// From: https://stackoverflow.com/questions/2387136/cross-browser-method-to-determine-vertical-scroll-percentage-in-javascript
function getScrollFraction() {
var h = document.documentElement,
b = document.body,
st = 'scrollTop',
sh = 'scrollHeight';
return (h[st]||b[st]) / ((h[sh]||b[sh]) - h.clientHeight);
}
function onScroll() {
updateImagePosition( getScrollFraction() );
}
updateImagePosition(0);
window.addEventListener('scroll', onScroll);
body {
min-height: 1000px;
}
svg {
display: block;
position: sticky;
top: 20px;
}
<svg id="text-container" viewBox="0 0 1000 194">
<path id="text-curve" d="M0 100s269.931 86.612 520 0c250.069-86.612 480 0 480 0" fill="none" stroke="gold"/>
<image id="cat" x="0" y="100" xlink:href="https://placekitten.com/40/40"/>
</svg>
推荐阅读
- authentication - 使用 SSO 对网络驱动器的用户进行身份验证
- c# - 如何获取云端分发IP?
- php - 使用 Guzzle 下载文件
- javascript - 如何在 Google Drive 的特定文件夹上使用 React Native 上传文档?
- scala - 如何在 Scala 中动态类型转换一个值?
- listview - ListView 小部件未在我的屏幕上显示并且无法正常工作(在 Flutter 中)
- javascript - 无法理解 requireJS 的 require() 函数
- python - AttributeError:模块“tensorflow_docs”没有属性“plots”
- xml - 如何使用 Powershell 使用 INI 文件自动创建 XML 文件?
- design-patterns - 分布式原子计数器