Advertisement

Interactive SVG Color Wheel

| by Vladimir | 2 min read | code by ikrProjects
Advanced

Tech & Dependencies

HTML CSS JavaScript
GSAP Chroma.js TinyColor2 RoundSlider

Features

  • Color Theory
  • Drag & Drop
  • SVG Morphing
  • Dynamic Theming

Browser Support

Chrome 80+ Edge 80+ Firefox 75+ Safari 13+

Core

This Interactive SVG Color Wheel is a sophisticated design tool built directly into the browser. It allows users to explore color harmonies - Analogous, Complementary, Triadic, Tetradic - by dragging a handle across a mathematically generated wheel. The interface reacts instantly, updating the background, UI elements, and data display with the selected palette, powered by the precision of Chroma.js and GSAP animations.

Core Technique

The logic combines SVG geometry with color manipulation libraries.

  1. Coordinate Mapping: The mouse position on the wheel is converted from Cartesian (x, y) to Polar coordinates (angle, radius). This angle determines the Hue (0-360), while the radius determines the Saturation (0-1).
  2. Harmony Calculation: When a base color is selected, TinyColor2 generates the related colors based on the chosen harmony rule (e.g., Triadic adds +120° and +240° hues).
  3. Visual Feedback: GSAP handles the smooth movement of the SVG handles (#tCW circles) and the morphing of the UI container path (morphSVG). The background gradients and text shadows are updated via CSS variables (--c0, --c1, etc.) injected by JavaScript.

Customization

The color calculation logic is centralized in the updateColor function. You can tweak how lightness affects the palette or add new harmony modes.

function updateColor(newColor, setBox) {
  // ... existing logic ...
  
  // Custom Harmony Example: Monochromatic
  if (paletteType == "monochromatic") {
     newColors = tinycolor2(newColor).monochromatic();
  }
}

The UI layout relies on SVG paths defined in the HTML. Changing the shape of the container involves editing the path data (d attribute) for #body and #corner.

Tips

1. Library Dependency: This project relies heavily on external libraries (chroma.js, tinycolor2, gsap, roundSlider). Ensure these are loaded correctly. In a production build (Webpack/Vite), you would install these via NPM (npm install chroma-js tinycolor2 gsap).

2. SVG Interaction: The interaction uses getBoundingClientRect on the SVG element. This can be sensitive to page scrolling or CSS transforms. If you place this component inside a scrollable modal or a transformed container, verify that the coordinate calculation logic (x = wheel.left + r - e.clientX) accounts for these offsets correctly.

Advertisement