SVGuitar

repository·master·Indexed 21 days ago

https://github.com/omnibrain/svguitar

A JavaScript/TypeScript library for rendering customizable SVG guitar chord charts in the browser. It features a fluent API via the SVGuitarChord class for configuring chord details and visual styles, including support for hand-drawn aesthetics through RoughJsRenderer and standard SVG rendering via SvgJsRenderer. The library allows for detailed definition of fingers, barres, and fret markers, and provides a plugin system to extend its API.

Tokens
7.9K
Snippets
19
Records
27
Agent score
72%

What's inside svguitar

  1. Quickstart: Render a chord chart using ES Modules

    master

    If you are using a module bundler, import SVGuitarChord from svguitar and use the fluent API to configure and draw the chart.

    import { SVGuitarChord } from 'svguitar'
    
    const chart = new SVGuitarChord('#chart')
    
    // draw the chart
    chart
      .configure({
        /* configuration */
      })
      .chord({
        /* chord */
      })
      .draw()
  2. Quickstart: Render a chord chart using UMD

    master

    To use SVGuitar without a build step, load the UMD script via a <script> tag and initialize the SVGuitarChord class by passing a CSS selector for the container element.

    <!--container of the chart-->
    <div id="chart"></div>
    
    <!--load umd script -->
    <script src="https://omnibrain.github.io/svguitar/js/svguitar.umd.js"></script>
    
    <script>
      // initialize the chart
      var chart = new svguitar.SVGuitarChord('#chart')
    
      // draw the chart
      chart
        .configure({
          /* configuration */
        })
        .chord({
          /* chord */
        })
        .draw()
    </script>
  3. Initialize RoughJsRenderer for hand-drawn style

    master

    The RoughJsRenderer class provides a hand-drawn aesthetic for chord diagrams using the roughjs library. It renders elements into an SVG container within a specified DOM element.

    To use it, instantiate the class by passing either an HTMLElement or a CSS selector string. The renderer will automatically create an SVG element, embed necessary definitions (like the 'Patrick Hand' font), and append it to the container.

    Note: The font is hard-coded to 'Patrick Hand' to ensure consistent hand-drawn styling via base64 embedding.

    import RoughJsRenderer from 'svguitar/src/renderer/roughjs/roughjs-renderer';
    
    // Using an HTMLElement
    const container = document.getElementById('chord-container')!;
    const renderer = new RoughJsRenderer(container);
    
    // Or using a selector
    const rendererBySelector = new RoughJsRenderer('#chord-container');
  4. Customize chart appearance with .configure()

    master

    The .configure() method accepts an optional object to override default visual settings.

    Common configuration options include:

    • orientation: 'vertical' or 'horizontal'.
    • style: 'normal' or 'handdrawn'.
    • strings: Number of strings (default 6).
    • frets: Number of frets (default 4).
    • tuning: Array of string labels (e.g., ['E', 'A', 'D', 'G', 'B', 'E']).
    • fingerColor, fingerTextColor, fingerSize: Styling for finger markers.
    • barreChordStyle: 'rectangle' or 'arc'.
    • fretMarkers: Array of fret numbers or objects (e.g., { fret: 11, double: true }) to show markers.
    • showFretMarkers: Boolean to enable/disable markers globally.
    • color: Global color for the chart (overridable by specific properties like titleColor or stringColor).
    • backgroundColor: Background color (use 'none' for transparent).
    chart.configure({
      orientation: 'vertical',
      style: 'normal',
      strings: 6,
      frets: 4,
      tuning: ['E', 'A', 'D', 'G', 'B', 'E'],
      fingerColor: '#000',
      fingerTextColor: '#FFF',
      barreChordStyle: 'rectangle',
      fretMarkers: [2, 4, 6, 8, { fret: 11, double: true }],
      showFretMarkers: true
    })
  5. Configure chord details with .chord()

    master

    The .chord() method defines the specific notes, fingers, and barres for the diagram.

    Key properties:

    • fingers: An array of [string, fret, text | options].
      • string: The string index (e.g., 2).
      • fret: The fret number or 'x' to denote an unplayed string.
      • text | options: A string label or an object containing { text, color, className, shape } (e.g., 'triangle').
    • barres: An array of objects defining barre chord spans. Each object includes fromString, toString, fret, and styling options like style ('rectangle' or 'arc').
    • title: The name of the chord.
    • position: The fret position (defaults to 1).
    new SVGuitarChord('#some-selector')
      .chord({
        fingers: [
          [2, 2, '2'],
          [3, 3, { text: '4', color: '#F00', className: 'red' }],
          [4, 3, { text: '3', shape: 'triangle' }],
          [6, 'x'],
        ],
        barres: [
          {
            fromString: 5,
            toString: 1,
            fret: 1,
            text: '1',
            color: '#0F0',
            textColor: '#F00',
            className: 'my-barre-chord',
            style: 'rectangle'
          },
        ],
        title: 'F# minor',
        position: 9,
      })
  6. Reference: SVGuitar configuration options

    master

    A complete list of available configuration keys for the .configure() method.

    /**
     * Orientation of the chord diagram. Chose between 'vertical' or 'horizontal'
     */
    orientation: 'vertical',
    
    /**
     * Select between 'normal' and 'handdrawn'
     */
    style: 'normal',
    
    /**
     * The number of strings
     */
    strings: 6,
    
    /**
     * The number of frets
     */
    frets: 4,
    
    /**
     * Default position if no positon is provided (first fret is 1)
     */
    position: 1,
    
    /**
     * These are the labels under the strings. Can be any string.
     */
    tuning: ['E', 'A', 'D', 'G', 'B', 'E'],
    
    /**
     * The position of the fret label (eg. "3fr")
     */
    fretLabelPosition: 'right',
    
    /**
     * The font size of the fret label
     */
    fretLabelFontSize: 38,
    
    /**
     * The font size of the string labels
     */
    tuningsFontSize: 28,
    
    /**
     * Size of a finger or barre relative to the string spacing
     */
    fingerSize: 0.65,
    
    /**
     * Color of a finger or barre
     */
    fingerColor: '#000',
    
    /**
     * The color of text inside fingers and barres
     */
    fingerTextColor: '#FFF',
    
    /**
     * The size of text inside fingers and barres
     */
    fingerTextSize: 22,
    
    /**
     * stroke color of a finger or barre. Defaults to the finger color if not set
     */
    fingerStrokeColor: '#000000',
    
    /**
     * stroke width of a finger or barre
     */
    fingerStrokeWidth: 0,
    
    /**
     * style of barre chords. Can be either 'rectangle' (default) or 'arc'.
     */
    barreChordStyle: 'rectangle',
    
    /**
     * stroke color of a barre chord. Defaults to the finger color if not set
     */
    barreChordStrokeColor: '#000000',
    
    /**
     * stroke width of a barre chord
     */
    barreChordStrokeWidth: 0,
    
    /**
     * Height of a fret, relative to the space between two strings
     */
    fretSize: 1.5,
    
    /**
     * The minimum side padding (from the guitar to the edge of the SVG) relative to the whole width.
     */
    sidePadding: 0.2,
    
    /**
     * The font family used for all letters and numbers
     */
    fontFamily: 'Arial, "Helvetica Neue", Helvetica, sans-serif',
    
    /**
     * Default title of the chart if no title is provided.
     */
    title: 'F# minor',
    
    /**
     * Font size of the title. 
     */
    titleFontSize: 48,
    
    /**
     * Space between the title and the chart
     */
    titleBottomMargin: 0,
    
    /**
     * Global color of the whole chart.
     */
    color: '#000000',
    
    /**
     * The background color of the chord diagram.
     */
    backgroundColor: 'none',
    
    /**
     * Barre chord rectangle border radius relative to the fingerSize
     */
    barreChordRadius: 0.25,
    
    /**
     * Size of the Xs and Os above empty strings relative to the space between two strings
     */
    emptyStringIndicatorSize: 0.6,
    
    /**
     * Global stroke width
     */
    strokeWidth: 2,
    
    /**
     * The width of the nut (only used if position is 1)
     */
    nutWidth: 10,
    
    /**
     * If this is set to `true`, the starting fret (eg. 3fr) will not be shown.
     */
    noPosition: false,
    
    /**
     * The color of the title (overrides color)
     */
    titleColor: '#000000',
    
    /**
     * The color of the strings (overrides color)
     */
    stringColor: '#000000',
    
    /**
     * The color of the fret position (overrides color)
     */
    fretLabelColor: '#000000',
    
    /**
     * The color of the tunings (overrides color)
     */
    tuningsColor: '#000000',
    
    /**
     * The color of the frets (overrides color)
     */
    fretColor: '#000000',
    
    /**
     * When set to true the distance between the chord diagram and the top of the SVG stayes the same
     */
    fixedDiagramPosition: false,
    
    /**
     * Text of the watermark
     */
    watermark: 'some watermark',
    
    /**
     * Font size of the watermark
     */
    watermarkFontSize: 12,
    
    /**
     * Color of the watermark (overrides color)
     */
    watermarkColor: '#000000',
    
    /**
     * Font-family of the watermark (overrides fontFamily)
     */
    watermarkFontFamily: 'Arial, "Helvetica Neue", Helvetica, sans-serif',
    
    /**
     * The title of the SVG (for accessibility)
     */
    svgTitle: 'Guitar chord diagram of F# minor',
    
    /**
     * The fret markers.
     */
    fretMarkers: [2, 4, 6, 8, { fret: 11, double: true }],
    
    /**
     * Flag to show or disable all fret markers globally.
     */
    showFretMarkers: true,
    
    /**
     * The shape of the fret markets.
     */
    fretMarkerShape: 'circle',
    
    /**
     * The size of a fret marker.
     */
    fretMarkerSize: 0.4,
    
    /**
     * The color of the fret markers.
     */
    fretMarkerColor: 'rgba(0, 0, 0, 0.2)',
    
    /**
     * The stroke color of the fret markers.
     */
    fretMarkerStrokeColor: '#000000',
    
    /**
     * The stroke width of the fret markers.
     */
    fretMarkerStrokeWidth: 0,
    
    /**
     * The distance between the double fret markers
     */
    doubleFretMarkerDistance: 0.4
  7. Use SvgJsRenderer for SVG rendering

    master

    SvgJsRenderer is a class used to render guitar chord graphics using the svg.js library. It extends a base Renderer class and provides methods to draw primitive shapes like lines, circles, rectangles, and text into an SVG container.

    To use it, instantiate the class by passing a QuerySelector or an HTMLElement which will serve as the container for the generated SVG.

    // Example instantiation
    const renderer = new SvgJsRenderer(document.getElementById('container'));
    
    // Drawing a line
    renderer.line(0, 0, 100, 100, 2, '#ff0000');
    
    // Drawing a circle
    renderer.circle(50, 50, 20, 2, '#000000', '#ffffff');
    
    // Clearing the canvas
    renderer.clear();
  8. Clear or remove the chord diagram

    master

    The SVGuitarChord class provides methods to manage the lifecycle of the rendered SVG in the DOM:

    • clear(): Clears the current contents of the renderer without removing the container.
    • remove(): Completely removes the diagram from the DOM.
  9. Render the chord diagram

    master

    After configuring the settings and defining the chord, call .draw() to render the SVG into the container. The draw() method returns an object containing the final width and height of the rendered SVG.

    const dimensions = chordChart.draw();
    console.log(`Rendered size: ${dimensions.width}x${dimensions.height}`);
  10. SvgJsRenderer API Reference

    master

    The SvgJsRenderer class provides the following public methods for drawing and managing the SVG canvas:

    Canvas Management

    • constructor(container: QuerySelector | HTMLElement): Initializes the SVG container and sets the default viewbox based on project constants.
    • clear(): void: Removes all children from the SVG.
    • remove(): void: Removes the entire SVG element from the DOM.
    • size(width: number, height: number): void: Updates the SVG viewbox dimensions.
    • background(color: string): void: Adds a rectangle covering 100% of the area with the specified fill color.
    • title(title: string): void: Adds an SVG <title> element for accessibility/tooltips.

    Drawing Primitives

    Each drawing method (except line, background, title, clear, remove, and size) returns a GraphcisElement object containing width, height, x, y, and a remove function to delete that specific element.

    • line(fromX: number, fromY: number, toX: number, toY: number, strokeWidth: number, color: string): void
    • text(text: string, x: number, y: number, fontSize: number, color: string, fontFamily: string, alignment: Alignment, classes?: string | string[], plain?: boolean): GraphcisElement
    • circle(x: number, y: number, diameter: number, strokeWidth: number, strokeColor: string, fill?: string, classes?: string | string[]): GraphcisElement
    • rect(x: number, y: number, width: number, height: number, strokeWidth: number, strokeColor: string, classes?: string | string[], fill?: string, radius?: number): GraphcisElement
    • triangle(x: number, y: number, size: number, strokeWidth: number, strokeColor: string, classes?: string | string[], fill?: string): GraphcisElement
    • pentagon(x: number, y: number, size: number, strokeWidth: number, strokeColor: string, fill: string, classes?: string | string[]): GraphcisElement
    • arc(x: number, y: number, width: number, height: number, direction: ArcDirection, strokeWidth: number, strokeColor: string, classes?: string | string[], fill?: string): GraphcisElement
  11. Manage the RoughJsRenderer lifecycle

    master

    Use the following methods to manage the state and lifecycle of the renderer:

    • clear(): Removes all existing children from the SVG and re-initializes the renderer and embedded definitions. Use this when you want to redraw the entire diagram.
    • remove(): Completely removes the SVG element from the DOM.
    • size(width, height): Updates the SVG viewBox attribute to the specified dimensions.
    • title(title): Sets the <title> element within the SVG for accessibility/metadata.
    // Clear the canvas for a new diagram
    renderer.clear();
    
    // Set the canvas size
    renderer.size(400, 400);
    
    // Remove the renderer entirely
    renderer.remove();