d3 is a well-known library for creating charts in Javascript but is also a great tool for drawing in general. In this post we take advantage of d3’s arc, color, and interpolateRainbow modules to create a simple color wheel. The “Scramble” and “Restore” buttons are included for fun to show how dead simple animations are with d3:
To get started, import dependencies and create the main SVG element:
Line 9SIZE is the outer width and height for the wheel.
Line 10SIZE_INNER is inner width and height for the wheel—the white circle in the middle.
Lines 11-12BANDS is the number of color bands. Calculate the BAND_WIDTH for each.
Lines 13-14MIN_OPACITY is the opacity for the innermost band. Calculate the OPACITY_STEP between each band.
Line 15COUNT is the number of colors in the wheel.
Line 16COLORS is an array of colors that we’ll bind as data. We create an array of COUNT elements that are mapped to colors generated by interpolateRainbow, a d3 function that accepts a number between 0 and 1 and returns a corresponding color value from the rainbow.
Lines 18-22 Create the main SVG element, attaching to an existing #color-wheel element in the DOM. Translate the origin to the center of the wheel.
Next create the wheel. We first create a g element for each band, then create a series of path elements on each band, bound to the COLORS data:
Lines 3-7 Use the arc generator to create an arc for a single color. We’ll reuse the arc by applying a rotate transform.
Lines 14-18 Adjust the opacity of the fill color using the color library.
Line 21 Rotate the color into position.
Line 22 Use the arc generator to create the path.
At this point you should have a color wheel that looks like the example at top. The “Scramble” and “Restore” buttons have click handlers that simply change the rotation of each band:
The above assumes we have a #buttons container element in the DOM where we attach the buttons. The “Scramble” button rotates each band to a random degree aligned with the existing colors. The “Restore” button simply returns the rotation to 0.
Comments
Leave a comment