Search code examples
csscss-animationssvg-filterscss-variables

How to control SVG filter attribute values using CSS?


I want to create animation in CSS, part of which I need to control the values of the SVG filter attributes.

Below, I try to call a CSS variable within the specularConstant attribute, and the browser returns an error.

Alternatively, is it possible to set the attribute using a selector in the CSS code, or is there any way to control an SVG attribute like this, via CSS?

Below a Reproducible Example:

@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>


Solution

  • You need to use the SVG <animate> element or JavaScript to do it.