首页 > 解决方案 > 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 订阅、所有可用的库,但我还没有深入研究它。

标签: javascriptcssanimationsvgscroll

解决方案


下面是一些示例代码,用于将 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>


推荐阅读