在 Jquery 事件上启动 Svg animateMotion

Launch Svg animateMotion on Jquery event

我目前正在研究 svg 动画。

我有一个 SVG 元素,它遵循带有 animateMotion 属性 的路径。

我的身材:

<g id="dart" transform="scale(-1,1) translate(-587, -145)">
    <path d="..." /> 
</g>

我的道路:

   <path id="motionPath" fill="none" stroke="none" stroke-miterlimit="10" d="..."/>

我的动画动画:

 <animateMotion xlink:href="#dart" dur="1s" begin="0s" fill="freeze" rotate="auto"><mpath xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#motionPath"></mpath></animateMotion>

效果很好。但是,它在加载页面 2 秒后开始移动。我想在 JS 事件上启动动画。事实上,我需要在页面中向下滚动以查看 SVG,当他可见时动画开始。

JS :

 var pos = $("#dart").offset().top;
    $(window).scroll(function(){
            var scrollTop=$(window).scrollTop();
                if(scrollTop>=pos){
                    /* --- start animation here with injecting --- */
                        var motion=document.createElementNS("http://www.w3.org/2000/svg","animateMotion");
                        motion.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", "#dart");
                        motion.setAttributeNS("http://www.w3.org/2000/svg", "dur", "1s");
                        motion.setAttributeNS("http://www.w3.org/2000/svg", "begin", "0s");
                        motion.setAttributeNS("http://www.w3.org/2000/svg", "fill", "freeze");
                        motion.setAttributeNS("http://www.w3.org/2000/svg", "rotate", "auto");

                        var mpath = document.createElementNS("http://www.w3.org/2000/svg","mpath");
                        mpath.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", "#motionPath");
                        motion.appendChild(mpath);
                        document.getElementById("target").appendChild(motion);
               }
    });

我试图注入(使用 createElementNS)<animateMotion> 或更改 begin 的值以便在事件上启动动画,但它不起作用。

如果有人有想法...

总结一下我最初在评论中写的内容...

您通常会通过设置开始属性将动画动作设置为在点击时开始,例如begin="dart.click"

jquery 旨在与 html 一起使用,任何 svg 支持大多是偶然的。因此,当它创建元素时,它会在 html 命名空间而不是 SVG 命名空间中创建它们。所以第一步是将您的代码转换为使用标准 DOM 方法,例如 document.createElementNS.

如果您确实使用 DOM 创建元素和属性,请注意在正确的命名空间中创建它们。

  • SVG 元素应该在 SVG 命名空间中创建

  • 大多数属性都在 null 命名空间中,应通过调用 element.setAttribute

  • 进行设置
  • xlink:href 属性在 xlink 命名空间中,但是必须通过调用 element.setAttributeNS 创建,将 xlink 命名空间作为第一个参数传递。