【问题标题】:Can a "super" SVG path be defined by children <path>?子 <path> 可以定义“超级”SVG 路径吗?
【发布时间】:2018-04-04 11:58:36
【问题描述】:

我想到 SVG 会以某种方式允许定义形状,这要归功于定义其边界的多个路径 - 隐式或显式关闭或打开。

我试过这个:

<svg
   xmlns:svg="http://www.w3.org/2000/svg"
   xmlns="http://www.w3.org/2000/svg"
   xmlns:xlink="http://www.w3.org/1999/xlink"
   width="200"
   height="200"
   viewBox="0 0 120 120"
   version="1.1">
  <defs>
    <path d="M 20,20 40,20 40,60 100,60 100,100" style="stroke:red;stroke-width:3px;" id="Border1" />
    <path d="M 100,100 L 20,100 20,20" style="stroke:blue;stroke-width:2px;" id="Border2" />
  </defs>
  <g style="fill: green">
    <use xlink:href = "#Border1"/>
    <use xlink:href = "#Border2"/>
  </g>
</svg>

用某种颜色填充组清楚地表明,每条路径都是单独考虑的,而不是作为一个整体考虑的。

有谁知道有没有办法做到这一点?

  1. 能够单独操作每个边框
  2. 通过边界定义一些形状

【问题讨论】:

    标签: svg path grouping fill


    【解决方案1】:

    没有。没有。

    SVG 工作组已经提出并讨论了类似的事情。但这就是目前为止。

    您可以编写一些 Javascript 来从一组边界路径构建区域。

    var regions = document.querySelectorAll("path.region");
    regions.forEach(function(region) {
      // Get the value of the "data-paths" attribute
      var borderIds = region.dataset.borders.split(',');
      var regionPath = "";
      // Find all the border paths for this region, and add them to the region's path data
      borderIds.forEach(function(id) {
        var borderDef = document.getElementById(id);
        var d = borderDef.getAttribute("d");
        if (regionPath === "") {
           // First border in region
           regionPath = d;
        } else {
           // Subsequent borders need their first 'M' changed to an 'L' to keep the path contiguous
           regionPath += 'L' + d.substr(1);
        }
      })
      region.setAttribute("d", regionPath);
    });
    <svg
       xmlns:svg="http://www.w3.org/2000/svg"
       xmlns="http://www.w3.org/2000/svg"
       xmlns:xlink="http://www.w3.org/1999/xlink"
       width="200"
       height="200"
       viewBox="0 0 120 120"
       version="1.1">
      <defs>
        <path d="M 20,20 40,20 40,60 100,60 100,100" style="stroke:red;stroke-width:3px;" id="Border1" />
        <path d="M 100,100 L 20,100 20,20" style="stroke:blue;stroke-width:2px;" id="Border2" />
      </defs>
      <path style="fill: green" class="region" data-borders="Border1,Border2"/>
    </svg>

    不是该代码仅在边框列表中的下一个边框路径从最后一个完成的位置开始时才有效。

    此外,此代码假定浏览器支持 SVG 元素上的 dataset 属性。如果您需要支持旧版浏览器,您可能需要改用getAttribute("data-borders")

    【讨论】:

      猜你喜欢
      • 2018-03-15
      • 2022-01-26
      • 2013-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-15
      • 1970-01-01
      相关资源
      最近更新 更多