My Blog

...

Music Scales With d3.js

This post is a small example that uses d3.js to dynamically shows different music scales.

The following buttons allow you to switch from a music scale to the other and to rotate the notes.

Some words about the implementation

The javascript is mainly inspired by the Donut Chart example.

The graphics is composed of 12 SVG groups; one per note. Each SVG group is composed of an arc and a text.

Ordinals are used to store data:

  • one containing the colors that are used to fill the arcs
  • one containing the notes that are used to set the text contents
Notes
1
var notes = d3.scale.ordinal().range([ "A", "A#/Bb", "B", "C", "C#/Db", "D", "E#/Eb", "E", "F", "F#/Gb", "G", "G#/Ab" ]);
  • one for each music scale; they are used to change the opacity of each SVG group
The Major Scale
1
var major = d3.scale.ordinal().range([1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1]);

When the reset button is clicked, an offset is incremented and the color and the text of each SVG group are changed:

Rotate button listener
1
2
3
4
5
6
7
8
9
10
11
12
13
14
d3.select("#rotate").on("click", function() {
    offset++;
    d3.selectAll(".note > path")
        .transition()
        .style("fill", function(d, i) {
            return color(i + offset);
        });

    d3.selectAll(".note > text")
        .transition()
        .text(function(d, i) {
            return notes(i + offset);
    });
});

When one of the scale button is clicked, the opacity of each SVG group is changed based on the ordinal of the selected scale.

Major Scale button listener
1
2
3
4
5
6
7
d3.select("#major").on("click", function() {
  d3.selectAll(".note")
  .transition()
  .style("opacity", function(d, i) {
      return major(i);
  });
});

Comments