无法在SVG图片中选择路径

时间:2014-12-22 09:34:27

标签: javascript html svg

我正在尝试为花朵SVG图像设置动画,使其看起来像花朵正在绘制,如this文章中所述。我已将当前代码包含在JSFiddle here中。

我似乎无法访问每个路径元素,我不太清楚为什么。我使用了文章中提供的Javascript代码,我下载/包含了我在网上找到的SVG花的svg HTML。当我运行代码时,Firefox,Safari和Chrome中的控制台会记录0,告诉我没有带有标记名称路径的元素。我不确定为什么会这样;任何人都可以解释为什么/我应该解决什么?

以下是javascript代码:

var paths = document.getElementsByTagName('path');
console.log(paths.length);
for (var i = 0; i < paths.length; i++) {
    var path = paths[i];
    var length = path.getTotalLength();
    // Clear any previous transition
    path.style.transition = path.style.WebkitTransition =
      'none';
    // Set up the starting positions
    path.style.strokeDasharray = length + ' ' + length;
    path.style.strokeDashoffset = length;
    // Trigger a layout so styles are calculated & the browser
    // picks up the starting position before animating
    path.getBoundingClientRect();
    // Define our transition
    path.style.transition = path.style.WebkitTransition =
      'stroke-dashoffset 2s ease-in-out';
    // Go!
    path.style.strokeDashoffset = '0';
}

以下是我的一些HTML代码:

<body>
<svg
   xmlns="http://www.w3.org/2000/svg"
   version="1.0"
   width="800px"
   height="800px"
   id="svg2385">
  <!-- <defs
     id="defs2387" />
  <g
     transform="translate(-163.06366,-372.39925)"
     id="layer1"> -->
    <path
       d="M 368.89962,527.3412 C 359.4568,464.38904 307.36168,439.5961 286.4323,430.39488 C 267.82968,422.21658 263.76952,407.10258 263.76952,407.10258 C 263.76952,407.10258 258.73335,424.09966 258.73335,432.28344 C 258.73335,440.46722 256.84479,478.86804 271.9533,510.97363 C 287.06182,543.07923 333.01689,554.41062 346.23685,570.14866 C 359.4568,585.8867 354.42063,613.58565 354.42063,613.58565 C 354.42063,613.58565 353.79111,591.55239 338.68259,578.33244 C 323.57407,565.11249 286.4323,565.11249 265.65809,527.3412 C 244.88388,489.5699 243.11868,419.10884 261.25144,392.62358 C 270.14221,379.63744 261.94361,399.48194 275.73043,412.13875 C 288.52321,423.88299 327.25144,435.53708 350.01398,458.72335 C 375.97069,485.16325 369.52915,528.60024 368.89962,527.3412 z"
       id="path2395"
       style="fill:#000000;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" />
    <path
       d="M 339.98723,553.05793 C 345.42186,528.07876 345.25711,516.73109 330.15128,500.99047 C 314.74039,484.93195 299.71749,490.29179 282.61153,461.86813 C 291.50944,496.40407 313.58336,493.78902 325.88728,512.78659 C 337.91025,531.35036 338.75504,552.37736 339.98723,553.05793 z"
       id="path3199"
       style="fill:#000000;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" />

1 个答案:

答案 0 :(得分:0)

解决了这个问题。因为我的Javascript代码是在我的HTML代码之前加载的,所以它注册了0个路径。我把脚本标签放在和之间,并且它起作用了。