无法选择 SVG 图片中的路径

Not able to select paths in SVG picture

本文关键字:路径 选择 SVG      更新时间:2023-09-26

我正在尝试对花朵SVG图像进行动画处理,使其看起来像花朵正在绘制自己,如本文所述。我已经在这里将我当前的代码包含在JSFiddle中。

我似乎无法访问每个路径元素,我也不太确定为什么。我使用了文章中提供的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" />
解决了

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