【问题标题】:How can I apply a pattern to an SVG element that ignores the element's transform values?如何将模式应用于忽略元素变换值的 SVG 元素?
【发布时间】:2021-01-26 20:21:01
【问题描述】:

我有一个修改内联 SVG 的 JavaScript 应用程序。我在 SVG 中有多个元素,它们都需要应用相同的背景图像。元素(路径)通过变换属性定位在 SVG 中。目前我正在元素上使用图案填充。有没有什么方法可以实现模式保持静止而不受元素变换的影响?

目前我有这个:

我想要这个:

(注意:我在第二张照片中硬烘焙了路径,无法在应用程序中使用)

编辑:

模式当前应用如下:

<defs>
    <pattern id="metallicgold" x="0" y="0" width="1240" height="775" patternUnits="userSpaceOnUse">
        <image xlink:href="img/gold-texture.png" />
    </pattern>
</defs>

元素的变换如下所示:

<path transform="translate(-445.0000396775016 -1950.3326958481455) rotate(317.2309439443859 2926.326416015625 2926.32666015625) scale(1 1)" style="fill: url('#metallicgold'); stroke: none;" d="M1951.326416015625,1951.32666015625L3901.326416015625,1951.32666015625L3901.326416015625,3901.32666015625L1951.326416015625,3901.32666015625L1951.326416015625,1951.32666015625Z" x="0" y="0"></path>

【问题讨论】:

  • 你能给我们看一些代码吗?
  • @Rojo 确定
  • 你试过玩transform-origin吗?
  • 我们可以在这里获得minimal reproducible example,即我们可以自己运行的完整的东西。

标签: javascript css svg


【解决方案1】:

如果您在变换形状时想要一个恒定的背景,您应该考虑使用带有 userSpaceOnUse filterUnits 的过滤器,除非变换很容易并且适用于所有填充的元素,在这种情况下,您可以在图案上使用 patternTransform 来反转对元素进行变换。

<svg width="800px" height="600px" viewBox="0 0 4000 4000">
  
  <defs>
    <filter id="brick" x="0" y="0" width="4000" height="4000" filterUnits="userSpaceOnUse">
        <feImage xlink:href="https://s-media-cache-ak0.pinimg.com/originals/c9/97/81/c99781a0ab356681cb038f70b1df68f1.jpg" x="0" y="0" width="4000" height="4000" preserveAspectRatio="xMinYMin meet"/>
      <feComposite operator="in" in2="SourceGraphic"/>
    </filter>
</defs>
  

  
  <g filter="url(#brick)">
  <path transform="translate(-445.00 -1950.33) rotate(317.23 2926.32 2926.32) scale(1 1)"  stroke="none" fill="red" d="M1951.326416015625,1951.32666015625L3901.326416015625,1951.32666015625L3901.326416015625,3901.32666015625L1951.326416015625,3901.32666015625L1951.326416015625,1951.32666015625Z" x="0" y="0"></path>
  </g>
  
    <rect x="1250" y="500" width="300" height="300" fill="blue"/>
  
    <g filter="url(#brick)">
  <circle cx="1000" cy="1000" r="500"/>
    </g>
  </svg>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-19
    • 1970-01-01
    • 2019-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多