Skip to content

Renderer: add gradient support #1352

@obiot

Description

@obiot

Summary

Add createLinearGradient() and createRadialGradient() to the renderer API, matching the Canvas 2D API.

Requirements

  • createLinearGradient(x0, y0, x1, y1) — returns a gradient object
  • createRadialGradient(x0, y0, r0, x1, y1, r1) — returns a gradient object
  • Gradient objects support addColorStop(offset, color)
  • Gradients can be used with setColor() for fill/stroke operations
  • Available on both Canvas and WebGL renderers

Use Cases

  • Sky backgrounds and atmospheric effects
  • Health bars, progress bars, energy meters
  • UI polish (button highlights, panel backgrounds)
  • Lighting/shadow approximations

Approach

Texture-based using the existing CanvasRenderTarget class :

  1. Create a GradientFill class that wraps color stops and gradient parameters
  2. When applied as a fill, render the gradient onto a small CanvasRenderTarget (e.g. 256x1 for linear, 256x256 for radial) using the native Canvas 2D gradient API (ctx.createLinearGradient / ctx.createRadialGradient)
  3. Use the resulting canvas as a texture fill via the existing pattern/texture pipeline
  4. Cache the texture — only regenerate when addColorStop() is called

Canvas renderer: The CanvasRenderTarget canvas gradient can be used directly as a CanvasPattern or set as ctx.fillStyle.

WebGL renderer: Upload the CanvasRenderTarget canvas as a WebGL texture. The existing batcher already handles texture-based fills. UV mapping controls the gradient direction/positioning across the geometry.

Why this approach:

  • Reuses existing CanvasRenderTarget infrastructure (already used by Text for offscreen rendering)
  • No custom shaders needed
  • Works within the existing batching system
  • Gradient texture memory is negligible (a 256x1 strip is ~1KB)
// Proposed API
const gradient = renderer.createLinearGradient(0, 0, 200, 0);
gradient.addColorStop(0, "#FF0000");
gradient.addColorStop(1, "#0000FF");
renderer.setColor(gradient);
renderer.fillRect(0, 0, 200, 100);

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions