Render SVG Piano graphics on web browser directly from PHP
PHPSVGPiano makes it possible for you to draw piano keys and chords directly into your browser as svg. No Javascript Required.
Since the file being rendered is in <svg/>
format, you can easily change the style using HTML or make some animation using Javascript. The choices are yours!
// get the class file
require_once "PHPSVGPiano.php";
//create a piano instance
$piano = new PHPSVGPiano();
//render an svg piano into the browser;
$piano->draw();
PHPSVGPiano draw()
method accepts comma separated musical notes as it's first parameter
$C_Major = "C, E, G";
$piano->draw( $C_Major );
In PHPSVGPiano;
Sharp
is represented with a plus +
sign
Flat
is represented with a minus -
sign.
So if you need to write a note like C#
, you would write C+
instead.
And when you need to write Cb
, you'd write C-
instead.
// Cmin#5 - C, Eb, G#
$C_Minor_Aug = "C, E-, G+";
$piano->draw( $C_Minor_Aug );
You can extend the piano octave by specifying how many octave should be rendered before calling the draw()
method.
// extend the piano to 2 octaves;
$piano->octaves = 2;
$piano->draw();
However, you can also specify the octave of a single note.
This will automatically increase the piano octave if the octave specified is higher than the default.
To specify a note octave, append a number to the note. For Example, C
or C4
represents the middle C
& C5
is an octave higher.
The default octave for any natural note is 4
// C Minor add9 = 1 - b3 - 5 - 9
$CmAdd9 = "C, E-, G, D5";
$piano->draw( $CmAdd9 );
// Let's try a different chord
// Minor7 = 1, b3, 5, b7;
$Bbmin7 = "B-, D-5, E5, A-5"; // B-Flat;
$piano->draw( $Bbmin7 );
You can display a title with the piano diagram by passing a string to the second parameter of draw()
method;
$piano->draw( "C, E-, G, B-", "C Minor 7" );
You can set the width of the piano octave and the height of the piano
$piano->octave_width = 300;
$piano->piano_height = 60;
$piano->draw();
You can return the svg result as string if you don't want to print the svg directly to the browser.
This can be achieved by passing a boolean
value false
to the 3rd parameter of draw()
method
$piano_svg = $piano->draw( null, null, false );
echo $piano_svg;
You can pass a name to the constructor method to classify all svg of that piano instance
$piano = new piano( "foo" );
$piano->draw( "E, G+, A", "E Sus2" );
Now the svg element will contain an attribute data-psvgp='foo'
That's it! Thanks for stopping by!
The idea of this project was inspired by SVGuitar
Though they have nothing in common in terms of language, they do have something in common in terms of creating visual instrument representations