【问题标题】:Why can I only use SourceGraphic as in2 in a feDeformationMap?为什么我只能在 feDeformationMap 中使用 SourceGraphic 作为 in2?
【发布时间】:2021-06-29 21:36:18
【问题描述】:

如果我在feDisplacementMap 中使用'SourceGraphic' 作为in2,事情看起来不错。但是,如果我使用其他任何东西,则不会应用变形。

因此,我必须先定义变形源,然后将过滤器应用于变形源,这很违反直觉,至少对我来说是这样。

例如,在下面的示例中,我必须定义圆,然后将过滤器应用于圆。在过滤器中,我使用feImage 加载小猫图像。但这对我来说是相反的。这有效:

<svg>
  <defs>
    <filter id="displace">
      <feImage href="https://placekitten.com/500/500" result="kitten" />
      <feDisplacementMap
        scale="10"
        xChannelSelector="R"
        yChannelSelector="R"
        in="kitten"
        in2="SourceGraphic"
      />
    </filter>
  </defs>
  <circle cx="50" cy="50" r="50" fill="#f00" filter="url(#displace)" />
</svg>

如您所见,对图像的一小部分应用置换非常痛苦,因为您必须首先自己创建置换贴图,并且它必须与图像具有相同的大小。像这样:

<g id="deformation-source" filter="url(#displace)">
  <rect x="0" y="0" width={imageWidth} height={imageHeight} fill={neutralToDeformation} />
  <circle cx="50" cy="50" r="50" fill="#f00" filter="url(#displace)" />
</g>

此外,对同一图像应用 2 种不同的变形,需要您放置会导致变形的对象,而不是执行以下操作:

<image href="kitten-url" filter="url(#filter-1)" />
<image href="kitten-url" filter="url(#filter-2)" />

我想做的是将小猫加载为 SVG image 标签,然后将过滤器应用于该图像,我将在 feImage 中加载圆圈,并引用对象的 id,我之前会在 defs 部分中定义。这不起作用:

<svg>
  <defs>
    <circle id="displacement-source" cx="50" cy="50" r="50" fill="#f00" />
    <filter id="displace">
      <feImage href="displacement-source" result="displacement-source" />
      <feDisplacementMap
        scale="10"
        xChannelSelector="R"
        yChannelSelector="R"
        in="SourceGraphic"
        in2="displacement-source"
      />
    </filter>
  </defs>
  <image href="https://placekitten.com/500/500" width="100" filter="url(#displace)" />
</svg>

我不确定我是不是在逆向思考这个问题,或者我是否遗漏了什么。这是怎么回事?

【问题讨论】:

    标签: svg svg-filters


    【解决方案1】:

    您可以在 feImage 中定义置换源,但它必须是定义为内联 URI 的完整图像才能跨浏览器兼容。

    <feImage width="500" height="500" xlink:href="data:image/svg+xml,%3Csvg width='247' height='34'etc. etc.
    

    请参阅this article for more detail on how to escape characters in the svg+xml format - 据我所知,与普通 HTML 转义相比,存在一些陷阱。

    如果您不关心 Firefox,您可以使用片段标识符而不是内联整个 SVG。

    <feImage width="500" height="500" xlink:href="#idOfElementYouWantToUse"/>
    

    还请记住,displacementMap 源有跨域安全规则 - 因此您不能使用来自另一个域的地图来置换图像(反之亦然 - 我对限制的运行方式有点模糊)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-17
      • 1970-01-01
      • 1970-01-01
      • 2019-03-12
      • 1970-01-01
      • 2020-05-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多