Animation with VexFlow & CSS

Experiment with VexFlow

by Gregory Ristow

HTML

<script src="https://npmcdn.com/vexflow/releases/vexflow-debug.js"></script>
<div id="container">
  <div id="boo"></div>
</div>
<div id="controls">
  <button id='add-note'>Add Note</button>
  <button id='right-answer'>Right Answer</button>
</div>

CSS

#container {
  width: 400px;
  height: 120px;
  overflow: hidden;
  border: 1px solid deeppink;
  marging: 10px;
}

#container > div {
  width: 10000px;
  height: 120px;
  white-space: nowrap;
}

#controls {
  padding: 15px;
}

#controls > button {
  margin: 5px;
}

.scroll {
  transition: transform 5s linear, opacity 0.5s ease-out, fill 0.2s linear;
}

.scrolling {
  transform: translate(-400px, 0);
}

.correct {
  opacity: 0;
}

.too-slow {
  transform: translate(-400px, 2000px);
}

JavaScript

// Basic setup boilerplate for using VexFlow with the SVG rendering context:
VF = Vex.Flow;

// Create an SVG renderer and attach it to the DIV element named "boo".
var div = document.getElementById("boo")
var renderer = new VF.Renderer(div, VF.Renderer.Backends.SVG);

// Configure the rendering context.
renderer.resize(500, 500);
var context = renderer.getContext();

// A tickContext is required to draw anything that would be placed
// in relation to time/rhythm, including StaveNote which we use here.
// In real music, this allows VexFlow to align notes from multiple
// voices with different rhythms horizontally. Here, it doesn't do much
// for us, since we'll be animating the horizontal placement of notes, 
// but we still need to add our notes to a tickContext so that they get
// an x value and can be rendered.
//
// If we create a voice, it will automatically apply a tickContext to our
// notes, and space them relative to each other based on their duration &
// the space available. We definitely do not want that here! So, instead
// of creating a voice, we handle that part of the drawing manually.
var tickContext = new VF.TickContext();

// Create a stave of width 10000 at position 10, 40 on the canvas.
var stave = new VF.Stave(10, 10, 10000)
.addClef('treble');

// Connect it to the rendering context and draw!
stave.setContext(context).draw();

var durations = ['8', '4', '2', '1'];

var notes = [
	['c', '#', '4'],
	['e', 'b', '5'],
	['g', '', '5'],
	['d', 'b', '4'],
	['b', 'bb', '3'],
	['a', 'b', '4'],
	['f', 'b', '5'],
].map(([letter, acc, octave]) => {
	const note = new VF.StaveNote({
    clef: 'treble',
    keys: [`${letter}${acc}/${octave}`],
    duration: durations[Math.floor(Math.random()*durations.length)],
  })
  .setContext(context)
  .setStave(stave);

  // If a StaveNote has an accidental, we must render it manually.
  // This is so that you get full control over whether to render
  // an accidental depending on the musical context. Here, if we
 ...