Skip to Content

The Piano class

If you need more control over the component lifecycle, you can use the Piano class.

Check the complete Piano API reference for more details.

Installation

pnpm add @music-ui/piano

Constructor

The Piano constructor accepts the following parameters:

PropertyTypeDefaultDescription
elementstring | HTMLElement#pianoThe container element or a valid CSS selector
octavesnumber2The amount of rendered octaves
startOctavenumber3The first octave being rendered
withFinalCbooleantrueRenders a final C key after the last octave
showOctavesbooleanfalseDisplays the octave number on every C note

Usage:

import { Piano } from "@music-ui/piano"; import "@music-ui/piano/styles.css"; // with default options const piano = new Piano(); // with passed options const piano = new Piano({ element: "#my-element", octaves: 4, startOctave: 2, showOctaves: true, });

Creating a new Piano does not render anything on screen. You have to call render() for that:

import { Piano } from "@music-ui/piano"; import "@music-ui/piano/styles.css"; const piano = new Piano(); piano.render();

Output:

Note highlight

You can highlight specific notes with Piano.setNotes:

const piano = new Piano({ element: "#my-element" }); piano.render(); piano.setNotes("C4 E4 G4");

And a C major chord is highlighted:

Always append the desired octave after the note in order to avoid ambiguity, e.g. C4 for middle C. This is especially relevant for any chord that crosses the octave line, e.g. A3 C#4 E4 G4.

Highlight different groups

If you want to split hands or outline specific voices, separate the groups via a comma:

const piano = new Piano({ octaves: 4, showOctaves: true }); piano.render(); piano.setNotes("C3 C4, E4 G4 C5");

Et voilà:

Display note labels

You can pass the labels to be displayed in the highlighted keys as a second parameter to Piano.setNotes:

const piano = new Piano(); piano.render(); piano.setNotes("F3 Ab3 C4 Eb4", "1 3 5 7");

You can skip labels for certain notes. Just use an underscore (_) as a placeholder:

const piano = new Piano(); piano.render(); piano.setNotes("F3 Ab3 C4 Eb4", "_ 3 _ 7");

Clear note highlight

Use piano.clearNotes:

const piano = new Piano(); piano.render(); piano.setNotes("C4 E4 G4"); // later on piano.clearNotes();

Set additional note state

Use piano.setPlayedNotes for playback scenarios when state changes over time but you still want to highlight the same set of notes:

const piano = new Piano({ octaves: 3 }); piano.render(); piano.setNotes("C4 E4 G4"); piano.setPlayedNotes("C4 G4");

See:

Clear played notes

Use piano.clearPlayedNotes:

const piano = new Piano(); piano.render(); piano.setNotes("C4 E4 G4"); piano.setPlayedNotes("C4 G4"); // later on piano.clearPlayedNotes();
Last updated on