Understanding SVG radialGradient fx and fy Attributes

This article explains the function of the fx and fy focal point attributes in an SVG <radialGradient>, how they differ from the center coordinates cx and cy, and how you can use them to create realistic 3D lighting and offset gradient effects.

What Are fx and fy?

In an SVG <radialGradient>, the fx and fy attributes define the coordinates of the focal point. The focal point is the exact location where the gradient begins (the 0% color stop).

By default, if fx and fy are not explicitly defined, they automatically inherit the values of cx and cy.

The Difference Between (cx, cy) and (fx, fy)

To understand fx and fy, you must distinguish between the gradient’s outer boundary and its starting point:

When fx and fy match cx and cy, the gradient radiates symmetrically in concentric circles from the center outward.

When fx and fy are shifted away from cx and cy, the gradient radiates outward from the offset focal point toward the stationary outer boundary defined by cx, cy, and r.

Practical Uses for fx and fy

The primary use of fx and fy is creating directional lighting and depth:

  1. 3D Spheres and Bubbles: By shifting the focal point toward the top-left (e.g., fx="30%" and fy="30%" while cx="50%" and cy="50%"), you can simulate a highlight from an external light source, turning a flat 2D circle into a realistic 3D sphere.
  2. Spotlight and Glow Effects: Off-centering the focal point allows you to create skewed cone-of-light or torch effects within fixed boundaries.
  3. Simulating Perspective: Adjusting focal points dynamically creates motion effects, such as a moving light across a stationary surface.

Example Usage

<svg width="200" height="200" viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">
  <defs>
    <radialGradient id="sphereShading" cx="50%" cy="50%" r="50%" fx="30%" fy="30%">
      <stop offset="0%" stop-color="#ffffff" />
      <stop offset="60%" stop-color="#0077ff" />
      <stop offset="100%" stop-color="#001a4d" />
    </radialGradient>
  </defs>

  <!-- Circle using the offset radial gradient -->
  <circle cx="100" cy="100" r="90" fill="url(#sphereShading)" />
</svg>

In this example, the gradient’s boundary stays centered at 50%, but the brightest point (#ffffff) originates at 30%, 30%, producing an off-center highlight.