Published
Edited
Aug 1, 2019
1 fork
2 stars
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
piano = Piano(width, height, widthRatio, heightRatio)
Insert cell
// Create a piano object that contains informations to draw piano keyboard
function Piano(width, height, widthRatio, heightRatio) {
const numKeys = 88; // # of keys (black/white) in a piano
// Function to check if keyIndex-th key is white or not(=black)
const isWhite = keyIndex => ![1, 4, 6, 9, 11].includes(keyIndex % 12);
// # of white keys with lower index than keyIndex-th key
const numLowerWhites = keyIndex => (
d3.range(keyIndex).reduce((acc, val) => (isWhite(val) ? acc+1 : acc), 0)
);
// Total # of white keys
const numWhiteKeys = numLowerWhites(numKeys);

// Dimension of keys
const whiteWidth = width / numWhiteKeys;
const blackWidth = whiteWidth * widthRatio;

return d3.range(numKeys).map(i => {
const offset = isWhite(i) ? 0 : -blackWidth/2;
return {
index: i,
type: isWhite(i) ? "white" : "black",
// Piano coordinate: x: lower to higher key, y: near to far
coord: {
x: {
min: whiteWidth * numLowerWhites(i) + offset,
max: whiteWidth * numLowerWhites(i) + offset + (isWhite(i) ? whiteWidth : blackWidth)
},
y: {
min: isWhite(i) ? 0 : (1 - heightRatio) * height,
max: height
}
}
};
})
}
Insert cell
height = width / 8;
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more