🔍

🎹 Piano Input Component

An interactive piano keyboard web component that renders keys in the light DOM and emits tone events when keys are clicked.

Now included in MOAT as moat-piano.


Features

  • Customizable octaves: Display 1 to 7 octaves (default: 2)
  • Configurable start note: Set the lowest MIDI note (default: 48 - C3)
  • Tuning control: Adjust the reference frequency for A4 (default: 440 Hz)
  • Event-driven: Emits tone events with MIDI number, frequency, and note name
  • Themable: CSS variables for customizing colors and sizes
  • Light DOM: No Shadow DOM - full styling control

Basic Usage

<piano-input></piano-input>

This renders a 2-octave keyboard starting at C3 (MIDI 48).


Demo

Last played: Click a key!

Attributes

octaves

Number of octaves to display (1-7)

<piano-input octaves="3"></piano-input>

start

MIDI number of the lowest key

<piano-input start="60"></piano-input>

tuning

Reference frequency for A4 in Hz

<piano-input tuning="432"></piano-input>

Events

The component dispatches a tone event when any key is clicked:

piano.addEventListener('tone', (event) => {
  const { midi, freq, note } = event.detail;
  console.log(`Played ${note}: MIDI ${midi}, ${freq.toFixed(2)} Hz`);
});

Theming

Customize the appearance using CSS variables:

piano-input {
  --white-key-color: #ffffff;
  --white-key-active: #e0e0e0;
  --black-key-color: #222222;
  --black-key-active: #555555;
  --key-width: 40px;
  --key-height: 120px;
}

Technical Details

Frequency Calculation

Frequencies are calculated using equal temperament tuning:

freq = tuning × 2^((midi - 69) / 12)

Where MIDI 69 is A4 at the specified tuning frequency.

Key Layout

  • White keys are arranged in a flex container
  • Black keys are absolutely positioned above white keys
  • Pattern follows standard piano layout: C, C#, D, D#, E, F, F#, G, G#, A, A#, B

Examples

3 octaves starting at C4

<piano-input octaves="3" start="60"></piano-input>

Alternative tuning (A4 = 432 Hz)

<piano-input tuning="432"></piano-input>

Full 88-key piano range

<piano-input octaves="7" start="21"></piano-input>

components published