### Install VexFlow using npm Source: https://github.com/0xfe/vexflow/wiki/Creating-Flexible-Uses-of-VexFlow Installs the VexFlow library using the Node Package Manager (npm). This is the primary method for adding VexFlow to your project. ```bash $ npm install vexflow ``` -------------------------------- ### Download Source and Install Dependencies Source: https://github.com/0xfe/vexflow/wiki/Build,-Test,-Release Clones the VexFlow repository and installs all necessary project dependencies using npm. This is the initial setup step for working with the project. ```bash git clone git@github.com:0xfe/vexflow.git cd vexflow npm install ``` -------------------------------- ### Initialize VexFlow Factory, EasyScore, and System Source: https://github.com/0xfe/vexflow/wiki/Using-EasyScore This snippet demonstrates the initial setup for VexFlow using the Factory, EasyScore, and System classes. The Factory handles rendering context, and EasyScore and System are generated through it. This is the starting point for creating musical notation. ```javascript var vf = new Vex.Flow.Factory({renderer: {elementId: 'boo'}}); var score = vf.EasyScore(); var system = vf.System(); ``` -------------------------------- ### Install and Use VexFlow with npm Source: https://github.com/0xfe/vexflow/wiki/VexFlow-3.0.9-Tutorial This snippet details how to install VexFlow using npm for use in bundled projects. It then provides an example of importing VexFlow and creating a musical score, similar to the script tag method. This is suitable for projects using module bundlers. ```bash npm install vexflow@3.0.9 ``` ```javascript import Vex from 'vexflow'; const f = new Vex.Flow.Factory({ renderer: { elementId: 'output', width: 500, height: 200 }, }); const score = f.EasyScore(); const system = f.System(); system .addStave({ voices: [ score.voice(score.notes('C#5/q, B4, A4, G#4', { stem: 'up' })), score.voice(score.notes('C#4/h, C#4', { stem: 'down' })), ], }) .addClef('treble') .addTimeSignature('4/4'); f.draw(); ``` -------------------------------- ### VexFlow Initialization: Renderer and Context Setup (JavaScript) Source: https://github.com/0xfe/vexflow/wiki/Understanding-Renderer-&-Context This snippet demonstrates the standard VexFlow initialization process. It sets up the rendering environment by creating a Renderer and obtaining a drawing context, typically for SVG output. This is the foundational step for drawing any music notation with VexFlow. ```javascript const { Renderer, Stave } = Vex.Flow; const div = document.getElementById("output"); const renderer = new Renderer(div, Renderer.Backends.SVG); renderer.resize(500, 250); const context = renderer.getContext(); ``` ```javascript const { Renderer, Stave } = Vex.Flow; ``` ```javascript const div = document.getElementById("output"); ``` ```javascript const renderer = new Renderer(div, Renderer.Backends.SVG); ``` ```javascript renderer.resize(500 /* width */, 250 /* height */); ``` ```javascript const context = renderer.getContext(); ``` ```javascript console.log(`Context is an instance of: ` + context.constructor.name); ``` -------------------------------- ### beginPath Source: https://github.com/0xfe/vexflow/blob/master/docs/api/classes/SVGContext.html Starts a new path on the canvas. ```APIDOC ## POST /beginPath ### Description Begins a new path for drawing shapes. ### Method POST ### Endpoint /beginPath ### Parameters None ### Response #### Success Response (200) - **context** (SVGContext) - The SVG context object. #### Response Example ```json { "context": "[SVGContext object]" } ``` ``` -------------------------------- ### Install VexFlow using npm Source: https://github.com/0xfe/vexflow/blob/master/README.md This command demonstrates how to install VexFlow into your project using npm, which is suitable for projects utilizing a module bundler. ```sh npm install vexflow ``` -------------------------------- ### Initialize VexFlow Factory and EasyScore Source: https://github.com/0xfe/vexflow/wiki/Creating-Flexible-Uses-of-VexFlow Initializes the VexFlow Factory, linking it to the HTML element by its ID, and sets up the EasyScore object for simplified note creation. This is a prerequisite for drawing music. ```javascript let vf = new Vex.Flow.Factory({ renderer: {elementId: 'new-song'} }); let score = vf.EasyScore(); let system = vf.System(); ``` -------------------------------- ### Run ESLint Independently Source: https://github.com/0xfe/vexflow/wiki/Migrating-to-ESLint This demonstrates how to install and run ESLint directly from the command line, independent of the Grunt build system. It requires navigating to the VexFlow root directory, installing dependencies, and then executing ESLint on a specified path. ```bash cd npm install eslint ``` -------------------------------- ### Drawing a Filled Triangle with VexFlow Context Source: https://github.com/0xfe/vexflow/wiki/Understanding-Renderer-&-Context Demonstrates how to draw and fill a triangle using the VexFlow context. It involves starting a path, defining line segments, closing the path, and applying a fill color. This is a fundamental example of path-based drawing. ```javascript context.beginPath() // start recording our pen's moves. .moveTo(0, 0) // pick up the pen and set it down at x=0, y=0 (top/left corner of the context). .lineTo(50, 0) // add a line toward the right (0, 0) => (50, 0). .lineTo(25, 50) // add a line to the left and down (50, 0) => (25, 50). .closePath() // add a line back to where the path started (0, 0) closing the triangle. .fill({ fill: 'yellow' }); // fill our triangle in yellow. ``` -------------------------------- ### Modifier Start XY API Source: https://github.com/0xfe/vexflow/blob/master/docs/api/classes/BarNote.html Gets the starting coordinates (x, y) for modifiers associated with the note. ```APIDOC ## GET /api/modifierStartXY ### Description Gets the coordinates for where modifiers begin for the note. This method is inherited from the Note class. ### Method GET ### Endpoint /api/modifierStartXY ### Parameters #### Query Parameters - **position** (number) - Optional - The position of the modifier. - **index** (number) - Optional - The index of the modifier. - **options** (any) - Optional - Additional options for calculating the start position. ### Request Example None ### Response #### Success Response (200) - **modifierStartXY** ({ x: number; y: number }) - An object containing the x and y coordinates. #### Response Example ```json { "modifierStartXY": { "x": 30, "y": 40 } } ``` ``` -------------------------------- ### Get Tie Start X Coordinate Source: https://github.com/0xfe/vexflow/blob/master/docs/api/classes/TabStave.html Returns the x-coordinate of the start of the stave's ties. This method is inherited from the base Stave class. ```javascript stave.getTieStartX(); ``` -------------------------------- ### VexFlow Initialization and SVG Context Setup (JavaScript) Source: https://github.com/0xfe/vexflow/wiki/Tutorial This JavaScript code initializes the VexFlow rendering engine, specifically configuring it to use the SVG backend. It creates a renderer attached to an HTML element and sets up the drawing context, which is essential for drawing musical elements. ```javascript const { Renderer, Stave, StaveNote, Voice, Formatter } = Vex.Flow; // Create an SVG renderer and attach it to the DIV element named "output". const div = document.getElementById("output"); const renderer = new Renderer(div, Renderer.Backends.SVG); // Configure the rendering context. renderer.resize(500, 500); const context = renderer.getContext(); ``` -------------------------------- ### Get Note Start X Coordinate Source: https://github.com/0xfe/vexflow/blob/master/docs/api/classes/TabStave.html Returns the x-coordinate of the start of the stave's notes. This method is inherited from the base Stave class. ```javascript stave.getNoteStartX(); ``` -------------------------------- ### Importing VexFlow Core Modules (JavaScript) Source: https://github.com/0xfe/vexflow/blob/master/demos/modules/both.html Demonstrates importing core VexFlow modules such as Vex, Flow, and StaveNote from different build files. This code logs the imported modules to the developer console. It assumes VexFlow is available in the project's build directory. ```javascript // import { Vex, Flow, StaveNote } from '../../build/esm/entry/vexflow.js'; // import { Vex, Flow, StaveNote } from '../../build/esm/entry/vexflow-debug.js'; // import { Vex, Flow, StaveNote, ArticulationTests } from '../../build/esm/entry/vexflow-debug-with-tests.js'; // import { Vex, Flow, StaveNote } from '../../build/esm/entry/vexflow-bravura.js'; // import { Vex, Flow, StaveNote } from '../../build/esm/entry/vexflow-gonville.js'; // import { Vex, Flow, StaveNote } from '../../build/esm/entry/vexflow-petaluma.js'; // import { Vex, Flow, StaveNote } from '../../build/esm/entry/vexflow-core.js'; const { Vex, Flow, StaveNote } = window.Vex; console.log(Vex); console.log(Flow); console.log(StaveNote); ``` -------------------------------- ### Get Fraction Remainder Source: https://github.com/0xfe/vexflow/blob/master/docs/api/classes/Fraction.html Returns the remainder component of a fraction. For example, for the fraction 5/2, the remainder is 1. ```javascript remainder(): number ``` -------------------------------- ### Get Fraction Quotient Source: https://github.com/0xfe/vexflow/blob/master/docs/api/classes/Fraction.html Returns the integer component of a fraction. For example, for the fraction 5/2, the quotient is 2. ```javascript quotient(): number ``` -------------------------------- ### System Class Documentation Source: https://github.com/0xfe/vexflow/blob/master/docs/api/classes/System.html Detailed documentation for the System class, including its constructor, properties, accessors, and methods. ```APIDOC ## System Class System implements a musical system, which is a collection of staves, each which can have one or more voices. All voices across all staves in the system are formatted together. ### Hierarchy * [Element](Element.html) * System ### Constructors #### `constructor(params?: SystemOptions)` * **Description**: Initializes a new instance of the System class. * **Parameters**: * `params` (SystemOptions) - Optional. An object containing options for the System. * **Returns**: `System` - The newly created System instance. ### Properties #### `static TEXT_FONT` * **Type**: `Required` * **Description**: Default font for text. This is not related to music engraving. Instead, see `Flow.setMusicFont(...fontNames)` to customize the font for musical symbols placed on the score. * **Inherited from**: `Element.TEXT_FONT` ### Accessors #### `font` * **Getter**: Returns the CSS compatible font string for the text font. * **Returns**: `string` * **Inherited from**: `Element.font` * **Setter**: Provides a CSS compatible font string (e.g., 'bold 16px Arial') that will be applied to text (not glyphs). * **Parameters**: * `f` (string) - The CSS font string. * **Returns**: `void` * **Inherited from**: `Element.font` #### `fontInfo` * **Getter**: Returns a copy of the current FontInfo object. * **Returns**: `Required` * **Inherited from**: `Element.fontInfo` * **Setter**: Sets the font information. * **Parameters**: * `fontInfo` (FontInfo) - The FontInfo object to set. * **Returns**: `void` * **Inherited from**: `Element.fontInfo` #### `fontSize` * **Getter**: Returns a CSS font-size string (e.g., '18pt', '12px', '1em'). * **Returns**: `string` * **Inherited from**: `Element.fontSize` * **Setter**: Sets the font size. The size can be a string (e.g., '10pt', '16px') or a number (interpreted as points). * **Parameters**: * `size` (string | number) - The font size to set. * **Returns**: `void` * **Inherited from**: `Element.fontSize` #### `fontSizeInPixels` * **Getter**: Returns the font size in `px`. * **Returns**: `number` * **Inherited from**: `Element.fontSizeInPixels` #### `fontSizeInPoints` * **Getter**: Returns the font size in `pt`. * **Returns**: `number` * **Inherited from**: `Element.fontSizeInPoints` ### Methods (Method documentation would typically follow here, listing each method with its description, parameters, and return types. Since the provided text only lists method names, they are omitted for brevity in this example.) ``` -------------------------------- ### Get Stave X Coordinate Source: https://github.com/0xfe/vexflow/blob/master/docs/api/classes/TabStave.html Returns the x-coordinate of the start of the stave. This method is inherited from the base Stave class. ```javascript stave.getX(); ``` -------------------------------- ### KeySigNote Methods Source: https://github.com/0xfe/vexflow/blob/master/docs/api/classes/KeySigNote.html Methods for configuring KeySigNote objects, including setting spacing, stave, style, tick context, tuplets, voices, width, shifts, and Y positions. ```APIDOC ## setRightDisplacedHeadPx /api/keysignature/notes ### Description Set spacing to the right of the notes. ### Method POST ### Endpoint /api/keysignature/notes/setRightDisplacedHeadPx ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **x** (number) - Required - The spacing value to set to the right of the notes. ### Request Example ```json { "x": 10 } ``` ### Response #### Success Response (200) - **KeySigNote** (object) - The updated KeySigNote object. #### Response Example ```json { "message": "Spacing set successfully." } ``` ## setStave /api/keysignature/notes ### Description Set the target stave for the note. ### Method POST ### Endpoint /api/keysignature/notes/setStave ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **stave** (Stave object) - Required - The Stave object to associate with the note. ### Request Example ```json { "stave": { ... stave object details ... } } ``` ### Response #### Success Response (200) - **KeySigNote** (object) - The updated KeySigNote object. #### Response Example ```json { "message": "Stave set successfully." } ``` ## setStyle /api/keysignature/notes ### Description Set the element style used to render the note. This can affect fill and stroke styles. ### Method POST ### Endpoint /api/keysignature/notes/setStyle ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **style** (ElementStyle object | undefined) - Optional - An object containing style properties like `fillStyle` and `strokeStyle`. ### Request Example ```json { "style": { "fillStyle": "red", "strokeStyle": "red" } } ``` ### Response #### Success Response (200) - **KeySigNote** (object) - The updated KeySigNote object. #### Response Example ```json { "message": "Style set successfully." } ``` ## setTickContext /api/keysignature/notes ### Description Set the `TickContext` for this note. ### Method POST ### Endpoint /api/keysignature/notes/setTickContext ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **tc** (TickContext object) - Required - The TickContext object to associate with the note. ### Request Example ```json { "tc": { ... tick context object details ... } } ``` ### Response #### Success Response (200) - **KeySigNote** (object) - The updated KeySigNote object. #### Response Example ```json { "message": "Tick context set successfully." } ``` ## setTuplet /api/keysignature/notes ### Description Attach this note to a new tuplet. ### Method POST ### Endpoint /api/keysignature/notes/setTuplet ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **tuplet** (Tuplet object) - Required - The Tuplet object to attach. ### Request Example ```json { "tuplet": { ... tuplet object details ... } } ``` ### Response #### Success Response (200) - **KeySigNote** (object) - The updated KeySigNote object. #### Response Example ```json { "message": "Tuplet attached successfully." } ``` ## setVoice /api/keysignature/notes ### Description Attach this note to a `Voice`. ### Method POST ### Endpoint /api/keysignature/notes/setVoice ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **voice** (Voice object) - Required - The Voice object to attach the note to. ### Request Example ```json { "voice": { ... voice object details ... } } ``` ### Response #### Success Response (200) - **KeySigNote** (object) - The updated KeySigNote object. #### Response Example ```json { "message": "Voice attached successfully." } ``` ## setWidth /api/keysignature/notes ### Description Set the width of the note. This is used by the formatter for positioning. ### Method POST ### Endpoint /api/keysignature/notes/setWidth ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **width** (number) - Required - The width of the note in pixels. ### Request Example ```json { "width": 50 } ``` ### Response #### Success Response (200) - **void** - Indicates the operation was successful. #### Response Example ```json { "message": "Width set successfully." } ``` ## setXShift /api/keysignature/notes ### Description Displace the note by `x` pixels. This is used by the formatter. ### Method POST ### Endpoint /api/keysignature/notes/setXShift ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **x** (number) - Required - The displacement in pixels. ### Request Example ```json { "x": 5 } ``` ### Response #### Success Response (200) - **KeySigNote** (object) - The updated KeySigNote object. #### Response Example ```json { "message": "X shift set successfully." } ``` ## setYs /api/keysignature/notes ### Description Set the Y positions for this note. Each Y value is associated with an individual pitch/key within the note/chord. ### Method POST ### Endpoint /api/keysignature/notes/setYs ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **ys** (array of numbers) - Required - An array of Y positions. ### Request Example ```json { "ys": [100, 110, 120] } ``` ### Response #### Success Response (200) - **KeySigNote** (object) - The updated KeySigNote object. #### Response Example ```json { "message": "Y positions set successfully." } ``` ## shouldIgnoreTicks /api/keysignature/notes ### Description Check if this note should be ignored by the tick system (e.g., bar notes, spacers). ### Method GET ### Endpoint /api/keysignature/notes/shouldIgnoreTicks ### Parameters #### Path Parameters None #### Query Parameters None ### Response #### Success Response (200) - **boolean** - True if the note should be ignored, false otherwise. #### Response Example ```json { "ignoreTicks": false } ``` ``` -------------------------------- ### Get Modifier Start Coordinates Source: https://github.com/0xfe/vexflow/blob/master/docs/api/classes/GlyphNote.html Retrieves the starting X and Y coordinates for note modifiers. This method can optionally accept parameters for position, index, and general options to refine the coordinate retrieval. It returns an array of objects, each containing 'x' and 'y' number properties. ```typescript getModifierStartXY(position?: number, index?: number, options?: any): { x: number; y: number; }[]; ``` -------------------------------- ### KeyManager Constructor Source: https://github.com/0xfe/vexflow/blob/master/docs/api/classes/KeyManager.html Initializes a new instance of the KeyManager class. ```APIDOC ## new KeyManager(key) ### Description Initializes a new instance of the KeyManager class. ### Method CONSTRUCTOR ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "key": "C" } ``` ### Response #### Success Response (200) - **KeyManager** (object) - An instance of the KeyManager class. #### Response Example ```json { "instance": "KeyManager" } ``` ``` -------------------------------- ### Create and Render a Single Voice with Notes and Chords in JavaScript Source: https://github.com/0xfe/vexflow/wiki/Tutorial This snippet demonstrates creating a single voice with multiple StaveNotes, including rests and chords. It then formats and renders this voice onto a VexFlow stave. Dependencies include StaveNote, Voice, and Formatter. ```javascript const notes = [ // A quarter-note C. new StaveNote({ keys: ["c/4"], duration: "q" }), // A quarter-note D. new StaveNote({ keys: ["d/4"], duration: "q" }), // A quarter-note rest. Note that the key (b/4) specifies the vertical // position of the rest. new StaveNote({ keys: ["b/4"], duration: "qr" }), // A C-Major chord. new StaveNote({ keys: ["c/4", "e/4", "g/4"], duration: "q" }), ]; // Create a voice in 4/4 and add above notes const voice = new Voice({ numBeats: 4, beatValue: 4 }); voice.addTickables(notes); // Format and justify the notes to 400 pixels. new Formatter().joinVoices([voice]).format([voice], 350); // Render voice voice.draw(context, stave); ``` -------------------------------- ### Get Font String Source: https://github.com/0xfe/vexflow/blob/master/docs/api/classes/Element.html Returns a CSS string representing the element's text font, for example, 'bold 10pt Arial'. ```typescript getFont(): string ``` -------------------------------- ### Manage Font Style Source: https://github.com/0xfe/vexflow/blob/master/docs/api/classes/Element.html Allows getting and setting the CSS font-style property for the element. The style is expected as a string, for example, 'italic'. ```typescript get fontStyle(): string set fontStyle(style: string): void ``` -------------------------------- ### SystemOptions Interface Source: https://github.com/0xfe/vexflow/blob/master/docs/api/interfaces/SystemOptions.html Details the properties available for configuring a VexFlow musical system, including width, justification, and spacing. ```APIDOC ## Interface SystemOptions ### Description Configuration options for creating and drawing musical systems. Allows control over system width, justification between voices, padding, and spacing. ### Method N/A (Interface definition) ### Endpoint N/A (Interface definition) ### Properties #### Optional Properties - **autoWidth** (boolean) - If true, the system calculates its width based on the voices and default stave padding. - **debugFormatter** (boolean) - Enables debugging for the formatter. - **details** (SystemFormatterOptions) - Provides detailed formatting options. - **factory** (Factory) - The factory used to create the system. - **formatIterations** (number) - The number of iterations for formatting. - **formatOptions** (FormatParams) - Specific parameters for formatting. - **noJustification** (boolean) - If true, disables justification between voices. - **noPadding** (boolean) - If true, disables default stave padding. - **spaceBetweenStaves** (number) - The space between staves in the system. - **width** (number) - The explicit width of the system. - **x** (number) - The x-coordinate of the system. - **y** (number) - The y-coordinate of the system. ### Request Example ```json { "autoWidth": true, "width": 800, "spaceBetweenStaves": 10, "noJustification": false } ``` ### Response #### Success Response (N/A for interface definition) This is an interface definition, not an endpoint with a direct response. #### Response Example N/A ``` -------------------------------- ### Get Element Font (VexFlow) Source: https://github.com/0xfe/vexflow/blob/master/docs/api/classes/Stem.html Retrieves the CSS string describing the font used for rendering the VexFlow element's text. For example, 'bold 10pt Arial'. Inherited from Element. ```javascript element.getFont(): string[]; ``` -------------------------------- ### Styling and Context Methods Source: https://github.com/0xfe/vexflow/blob/master/docs/api/classes/Tickable.html Methods for applying styles and managing rendering contexts. ```APIDOC ## POST /0xfe/vexflow/applyStyle ### Description Applies the element's style to the specified rendering context. ### Method POST ### Endpoint /0xfe/vexflow/applyStyle ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **context** (RenderContext) - Optional - The rendering context to apply the style to. - **style** (ElementStyle) - Optional - The style object to apply. ### Request Example ```json { "context": "RenderContextObject", "style": { "fill": "#000000", "stroke": "#ffffff" } } ``` ### Response #### Success Response (200) - **tickable** (Tickable) - The tickable element itself, allowing for chaining. #### Response Example ```json { "tickable": "TickableObject" } ``` ``` ```APIDOC ## POST /0xfe/vexflow/checkContext ### Description Validates and returns the rendering context for the element. ### Method POST ### Endpoint /0xfe/vexflow/checkContext ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json {} ``` ### Response #### Success Response (200) - **renderContext** (RenderContext) - The validated rendering context. #### Response Example ```json { "renderContext": "RenderContextObject" } ``` ``` ```APIDOC ## POST /0xfe/vexflow/getContext ### Description Returns the rendering context associated with the element. ### Method POST ### Endpoint /0xfe/vexflow/getContext ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json {} ``` ### Response #### Success Response (200) - **renderContext** (RenderContext | undefined) - The rendering context object, or undefined if not available. #### Response Example ```json { "renderContext": "RenderContextObject" } ``` ``` -------------------------------- ### JavaScript: VexFlow Test Runner Setup Source: https://github.com/0xfe/vexflow/blob/master/tests/formatter/index.html Sets up and runs tests for VexFlow asynchronously. It initializes the VexFlow registry, creates frame stacks for each test, and uses `setTimeout` to defer execution, preventing UI blocking. It also includes event listeners for a 'START'/'STOP' button to control test execution. ```javascript function defer(fn) { setTimeout(fn, 0); } function message(text, enabled = false) { const button = document.querySelector('#go'); if (!enabled) { button.setAttribute('disabled', true); } else { button.removeAttribute('disabled'); } button.innerHTML = text; } document.addEventListener('DOMContentLoaded', () => { const iterations = 100; VF.Registry.enableDefaultRegistry(); let frameStacks = []; Object.keys(Tests).forEach((t) => { const test = Tests[t]; console.log('Running', t, test.options); const frameStack = new FrameStack(t, iterations, { prefix: `test-${t}-`, ...test.options, }); defer(() => { message('Running ' + t); for (let i = 0; i < iterations; i++) { test.fn(frameStack.get(i), i, { ...test.options }); } }); frameStack.install(); frameStacks.push(frameStack); }); let running = false; const button = document.querySelector('#go'); button.addEventListener('click', () => { frameStacks.forEach((f) => { if (running) { f.stop(); } else { f.start(); } }); running = !running; if (running) { button.innerHTML = 'STOP'; } else { button.innerHTML = 'START'; } }); defer(() => { message('START', true); }); }); ``` -------------------------------- ### Import VexFlow ES Module and Dynamically Load Music Fonts Source: https://github.com/0xfe/vexflow/blob/master/demos/modules/module.html This alternative method imports VexFlow and asynchronously loads music fonts. This approach reduces the initial bundle size but introduces a slight latency for font loading. ```javascript import Vex from '../../build/esm/entry/vexflow-core.js'; await Vex.Flow.fetchMusicFont('Bravura'); Vex.Flow.setMusicFont('Bravura'); await Vex.Flow.fetchMusicFont('Gonville'); Vex.Flow.setMusicFont('Gonville'); await Vex.Flow.fetchMusicFont('Petaluma'); Vex.Flow.setMusicFont('Petaluma'); ``` -------------------------------- ### HTML Structure for VexFlow Rendering Source: https://github.com/0xfe/vexflow/wiki/Creating-Flexible-Uses-of-VexFlow Defines the HTML element where the VexFlow musical staff will be rendered. The `id` attribute must match the `elementId` specified in the VexFlow Factory initialization. ```html
``` -------------------------------- ### Static Factory Methods for TabTie/TabSlide Source: https://github.com/0xfe/vexflow/blob/master/docs/api/classes/TabSlide.html Static methods to create different types of ties and slides. ```APIDOC ## Static Factory Methods ### createHammeron #### Description Creates a hammer-on tie. #### Method POST #### Endpoint /tie/createHammeron #### Parameters ##### Path Parameters None ##### Query Parameters None ##### Request Body - **notes** (TieNotes) - Required - The notes for the hammer-on. ### createPulloff #### Description Creates a pull-off tie. #### Method POST #### Endpoint /tie/createPulloff #### Parameters ##### Path Parameters None ##### Query Parameters None ##### Request Body - **notes** (TieNotes) - Required - The notes for the pull-off. ### createSlideDown #### Description Creates a slide-down effect. #### Method POST #### Endpoint /slide/createSlideDown #### Parameters ##### Path Parameters None ##### Query Parameters None ##### Request Body - **notes** (TieNotes) - Required - The notes for the slide. ### createSlideUp #### Description Creates a slide-up effect. #### Method POST #### Endpoint /slide/createSlideUp #### Parameters ##### Path Parameters None ##### Query Parameters None ##### Request Body - **notes** (TieNotes) - Required - The notes for the slide. ### Request Example (createHammeron) ```json { "notes": { "first_note": "E4", "last_note": "G4" } } ``` ### Response Example (createHammeron) ```json { "tie_id": "hammeron-123", "message": "Hammer-on created successfully" } ``` ### Request Example (createPulloff) ```json { "notes": { "first_note": "C5", "last_note": "A4" } } ``` ### Response Example (createPulloff) ```json { "tie_id": "pulloff-456", "message": "Pull-off created successfully" } ``` ### Request Example (createSlideDown) ```json { "notes": { "first_note": "D4", "last_note": "F4" } } ``` ### Response Example (createSlideDown) ```json { "slide_id": "slidedown-789", "message": "Slide down created successfully" } ``` ### Request Example (createSlideUp) ```json { "notes": { "first_note": "G3", "last_note": "B3" } } ``` ### Response Example (createSlideUp) ```json { "slide_id": "slideup-012", "message": "Slide up created successfully" } ``` ``` -------------------------------- ### Generate PDF Score using Node.js and VexFlow Source: https://github.com/0xfe/vexflow/wiki/VexFlow-4-Tutorial This Node.js script demonstrates how to generate a musical score and save it as a PDF. It utilizes VexFlow for score rendering, jsdom to create a virtual DOM environment, and jsPDF with svg2pdf.js for PDF generation. Ensure you have installed the necessary packages: `npm install vexflow jsdom jspdf svg2pdf.js`. ```javascript import { Vex, Stave, StaveNote, Formatter } from "vexflow"; import { JSDOM } from "jsdom"; import { jsPDF } from "jspdf"; import "svg2pdf.js"; const VF = Vex.Flow; console.log("VexFlow Build: " + JSON.stringify(VF.BUILD)); const dom = new JSDOM('
'); global.window = dom.window; global.document = dom.window.document; // Create an SVG renderer and attach it to the DIV element named "vf". const div = document.getElementById("vf"); const renderer = new VF.Renderer(div, VF.Renderer.Backends.SVG); // Configure the rendering context. renderer.resize(200, 200); const context = renderer.getContext(); context.setFont("Arial", 10); const stave = new Stave(10, 0, 190); // Add a clef and time signature. stave.addClef("treble").addTimeSignature("4/4"); // Connect it to the rendering context and draw! stave.setContext(context).draw(); const notes = [ new StaveNote({ keys: ["c/4"], duration: "q" }), new StaveNote({ keys: ["d/4"], duration: "q" }), new StaveNote({ keys: ["b/4"], duration: "qr" }), new StaveNote({ keys: ["c/4", "e/4", "g/4"], duration: "q" }), ]; // Helper function to justify and draw a 4/4 voice. Formatter.FormatAndDraw(context, stave, notes); const doc = new jsPDF(); const svgElement = div.childNodes[0]; doc.svg(svgElement).then(() => doc.save("score.pdf")); console.log("Saved score.pdf"); ``` -------------------------------- ### Create and Render Multiple Voices with Notes in JavaScript Source: https://github.com/0xfe/vexflow/wiki/Tutorial This snippet shows how to create and render multiple voices simultaneously. It defines two sets of notes, assigns them to separate voices, and then formats and draws both voices on the same stave. This is useful for polyphonic music. ```javascript const notes = [ new StaveNote({ keys: ["c/5"], duration: "q", }), new StaveNote({ keys: ["d/4"], duration: "q", }), new StaveNote({ keys: ["b/4"], duration: "qr", }), new StaveNote({ keys: ["c/4", "e/4", "g/4"], duration: "q", }), ]; const notes2 = [ new StaveNote({ keys: ["c/4"], duration: "w", }), ]; // Create a voice in 4/4 and add above notes const voices = [ new Voice({ numBeats: 4, beatValue: 4, }).addTickables(notes), new Voice({ numBeats: 4, beatValue: 4, }).addTickables(notes2), ]; // Format and justify the notes to 400 pixels. new Formatter().joinVoices(voices).format(voices, 350); // Render voices. voices.forEach(function (v) { v.draw(context, stave); }); ``` -------------------------------- ### Get the global VexFlow object Source: https://github.com/0xfe/vexflow/blob/master/docs/api/classes/ClefNote.html Retrieves the global VexFlow object, which provides access to the library's core functionalities and namespaces. This is often the starting point for using VexFlow in a project. It returns the global `Vex` object. ```typescript import { Vex } from 'vexflow'; function getGlobalObject(): any { return Vex; } ``` -------------------------------- ### CSS Styling for Music Rendering Area Source: https://github.com/0xfe/vexflow/wiki/Creating-Flexible-Uses-of-VexFlow Provides basic CSS to style the container for the VexFlow musical staff. This includes setting margins, padding, background color, and dimensions for the rendering area. ```css .music-render { margin: 10px auto; padding: 10px; background-color: rgba(255, 255, 255, 0.85); width: 600px; height: 150px; } ``` -------------------------------- ### Lookup Metric Example (VexFlow) Source: https://github.com/0xfe/vexflow/wiki/VexFlow-Font-Rendering Demonstrates how to retrieve a specific metric value from the current music font using the `lookupMetric` method. It shows how to provide a metric path and an optional default value, handling cases where the metric might not be found. ```javascript const clefPointSize = Tables.currentMusicFont().lookupMetric("clef.small.point", 40); renderClef("treble", clefPointSize); ``` -------------------------------- ### Include VexFlow via Script Tag Source: https://github.com/0xfe/vexflow/blob/master/README.md This snippet shows how to add VexFlow to a web page using a ` ``` -------------------------------- ### Flow Constructor Source: https://github.com/0xfe/vexflow/blob/master/docs/api/classes/Flow.html Information about how to instantiate the Flow class. ```APIDOC ## Flow Constructor ### Description Initializes a new instance of the Flow class. ### Method `new` ### Endpoint N/A ### Parameters None ### Request Example ```javascript const flow = new Flow(); ``` ### Response #### Success Response (200) - **Flow** (object) - An instance of the Flow class. #### Response Example ```json { "instance": "Flow object" } ``` ``` -------------------------------- ### Include VexFlow Debug Script in HTML Source: https://github.com/0xfe/vexflow/wiki/Creating-Flexible-Uses-of-VexFlow Adds the VexFlow debug script to your HTML file. This script is necessary for VexFlow to render musical notation correctly. It should be included in the `` or before the closing `` tag. ```html ``` -------------------------------- ### Rendering Context - State Management and Styling Source: https://github.com/0xfe/vexflow/blob/master/docs/api/classes/RenderContext.html This section describes methods for managing the rendering state, such as saving/restoring context, and setting styles. ```APIDOC ## POST /api/render/fill ### Description Fills the current path or shape with the current fill style. ### Method POST ### Endpoint /api/render/fill ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **attributes** (any) - Optional - Attributes to apply during fill. ### Request Example ```json { "attributes": { "fillStyle": "blue" } } ``` ### Response #### Success Response (200) - **context** (object) - The updated render context. #### Response Example ```json { "context": "[RenderContext object]" } ``` ## POST /api/render/getFont ### Description Retrieves the current font style of the rendering context. ### Method POST ### Endpoint /api/render/getFont ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json {} ``` ### Response #### Success Response (200) - **font** (string) - The current font style. #### Response Example ```json { "font": "12pt Arial" } ``` ## POST /api/render/restore ### Description Restores the rendering context to its most recently saved state. ### Method POST ### Endpoint /api/render/restore ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json {} ``` ### Response #### Success Response (200) - **context** (object) - The updated render context. #### Response Example ```json { "context": "[RenderContext object]" } ``` ## POST /api/render/save ### Description Saves the current state of the rendering context (e.g., transformations, styles). ### Method POST ### Endpoint /api/render/save ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json {} ``` ### Response #### Success Response (200) - **context** (object) - The updated render context. #### Response Example ```json { "context": "[RenderContext object]" } ``` ## POST /api/render/scale ### Description Scales the rendering context by the specified factors. ### Method POST ### Endpoint /api/render/scale ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **x** (number) - Required - The scaling factor for the x-axis. - **y** (number) - Required - The scaling factor for the y-axis. ### Request Example ```json { "x": 2, "y": 2 } ``` ### Response #### Success Response (200) - **context** (object) - The updated render context. #### Response Example ```json { "context": "[RenderContext object]" } ``` ## POST /api/render/setBackgroundFillStyle ### Description Sets the background fill style for the rendering context. ### Method POST ### Endpoint /api/render/setBackgroundFillStyle ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **style** (string) - Required - The fill style to set (e.g., color string, gradient). ### Request Example ```json { "style": "#f0f0f0" } ``` ### Response #### Success Response (200) - **context** (object) - The updated render context. #### Response Example ```json { "context": "[RenderContext object]" } ``` ``` -------------------------------- ### HTML Button to Trigger Note Rendering Source: https://github.com/0xfe/vexflow/wiki/Creating-Flexible-Uses-of-VexFlow An HTML input button that, when clicked, calls the `writeNote` JavaScript function with specific note pitch and rhythm values. This provides a user interface to add notes to the VexFlow staff. ```html ``` -------------------------------- ### Create and Draw a VexFlow Stave Source: https://github.com/0xfe/vexflow/wiki/Understanding-Renderer-&-Context Demonstrates how to instantiate a VexFlow Stave object with its position and width, and then draw it to the rendering context. It highlights the requirement of setting a context before drawing to avoid runtime errors. ```javascript const stave = new Stave(110 /* x */, 60 /* y */, 90 /* width */); stave.setContext(context).draw(); ``` -------------------------------- ### JavaScript Function to Write and Render Notes Source: https://github.com/0xfe/vexflow/wiki/Creating-Flexible-Uses-of-VexFlow A JavaScript function that writes a single musical note to the VexFlow staff. It dynamically sets the time signature based on the rhythm provided and then draws the note. Error handling for rhythm is included. ```javascript function writeNote(pitch, rhythm){ document.getElementById('score'); // add additional if statements to include more rhythmic options if (rhythm === '/8') { score.set({time: "1/8"}) } else if (rhythm === '/q') { score.set({time: "1/4"}); } else if (rhythm === '/h') { score.set({time: "1/2"}); } system.addStave({ voices: [score.voice(score.notes(pitch + rhythm))] }).addClef('treble'); vf.draw(); } ```