首页 > 解决方案 > 如何使用 CSS 控制 SVG 过滤器属性值?

问题描述

我想在 CSS 中创建动画,其中一部分我需要控制 SVG 过滤器属性的值。

下面,我尝试在specularConstant属性中调用 CSS 变量,浏览器返回错误。

或者,是否可以使用 CSS 代码中的选择器设置属性,或者有没有办法通过 CSS 控制这样的 SVG 属性?

下面是一个可重现的例子:

@property --illumination-power {
  syntax: '<number>';
  initial-value: 1;
  inherits: true
}

:root {
  animation: my-animation 5s;
}

@keyframes my-animation {
  0% {
    --illumination-power: 0;
  }
  100% {
    --illumination-power: 1.2;
  }
}

body {
  margin: 0;
  background-color: black;
}
<svg width="100vw" height="100vh">
  <defs>
    <filter id="spotlight">
      <feSpecularLighting specularConstant="var(--illumination-power)"
      specularExponent="10" lighting-color="white">
        <fePointLight x="200" y="100" z="70"/>
      </feSpecularLighting>
    </filter>
  </defs>

  <rect id="light-background" x="-500%" y="-500%" width="1000%" height="1000%" fill-opacity="0" filter="url(#spotlight)"/>
</svg>

标签: csscss-animationssvg-filterscss-variables

解决方案


您需要使用 SVG<animate>元素或 JavaScript 来执行此操作。


推荐阅读