ailon / piano-chart

Piano Chart - JavaScript library to visualize musical notes on a piano keyboard
MIT License
66 stars 10 forks source link

piano-chart — JavaScript library to visualize musical notes on a piano keyboard

The purpose of piano-chart is to allow developers to include visual representation of musical notes on a piano keyboard.

See it "in action" at PianoShow.me.

Installation

npm install piano-chart

or

yarn add piano-chart

Usage

The basics

All you need to do to display your notes on a piano chart is create the instrument by specifying a container to render into, and then tell it what notes to "press". Here's how you would show a D Major chord in 4th octave:

import { Instrument } from "piano-chart";

const piano = new Instrument(document.getElementById('pianoContainer'));
piano.create();

piano.keyDown("D4");
piano.keyDown("F#4");
piano.keyDown("A4");

And you should get this:

D Major chord on a 49-key keyboard

Configuration

As you can see it's very easy to get a simple piano chart. But there are more things you can customize to your liking.

This examples changes the keyboard to smaller one and also highlights the notes in D Major scale.

import { Instrument } from "piano-chart";

const piano = new Instrument(document.getElementById('pianoContainer'), {
    startOctave: 3,
    endOctave: 5,
    highlightedNotes: ["D", "E", "F#", "G", "A", "B", "C#"],
    specialHighlightedNotes: [{ note: "D" }],
  }
);
piano.create();

piano.keyDown("D4");
piano.keyDown("F#4");
piano.keyDown("A4");

This is what you get as a result:

D Major chord on a 49-key keyboard

You pass configuration object as a second parameter to the Instrument constructor and you can also change most of them later by calling the applySettings() method.

Available settings:

Methods

Events

piano-chart can raise events when keys are clicked with a mouse. To handle these events you need to add listeners using addKeyMouseDownListener(), addKeyMouseUpListener() and remove them using removeKeyMouseDownListener() and removeKeyMouseUpListener() when no longer needed.

All handlers receive an argument of INoteValue type:

interface INoteValue {
  note: Note;
  accidental?: Accidetnal;
  octave?: number;
}

Note that you need to route this note back to the keyDown()/keyUp() methods if you want for these clicks to result in visible key presses.

License

piano-chart is distributed under the MIT License.

Copyright by Alan Mendelevich.