OpenSheetMusicDisplay
    Preparing search index...

    Class OpenSheetMusicDisplay

    The main class and control point of OpenSheetMusicDisplay.
    It can display MusicXML sheet music files in an HTML element container.
    After the constructor, use load() and render() to load and render a MusicXML file.

    Index
    • Creates and attaches an OpenSheetMusicDisplay object to an HTML element container.
      After the constructor, use load() and render() to load and render a MusicXML file.

      Parameters

      • container: string | HTMLElement

        The container element OSMD will be rendered into.
        Either a string specifying the ID of an HTML container element,
        or a reference to the HTML element itself (e.g. div)

      • options: IOSMDOptions = ...

        An object for rendering options like the backend (svg/canvas) or autoResize.
        For defaults see the OSMDOptionsStandard method in the [[OSMDOptions]] class.

      Returns OpenSheetMusicDisplay

    autoResizeEnabled: boolean
    backendType: BackendType
    container: HTMLElement
    cursors: Cursor[] = []
    cursorsOptions: CursorOptions[]

    Options from which OSMD creates cursors in enableOrDisableCursors().

    drawBottomLine: boolean
    drawBoundingBox: string
    drawingParameters: DrawingParameters
    drawSkyLine: boolean
    followCursor: boolean
    layoutContainerWidth: number

    The container's content width (getContainerContentWidth()) the last layout was made for: by render(), or at the start of incremental rendering. Turning autoResize on re-renders a rendered sheet only if the width differs from it.

    loadUrlTimeout: number = 5000

    Timeout in milliseconds used in osmd.load(string) when string is a URL.

    needBackendUpdate: boolean
    OnRender: (info: IRenderInfo) => void = undefined

    A function that is called after each render: at the end of render() and of each batch of renderNext(), also of the renders OSMD starts itself (autoResize, enableIncrementalRenderingOnScroll()). A render replaces the SVG elements, so this is the place to color them or add listeners to them again. Also the option onRender.

    OnXMLRead: (xml: string) => string = ...

    A function that is executed when the XML has been read. The return value will be used as the actual XML OSMD parses, so you can make modifications to the xml that OSMD will use. By default it returns the XML unchanged. It can also be set by the onXMLRead option, and osmd.setOptions() keeps it when the option is left out.

    resizeHandlerAttached: boolean
    sheet: MusicSheet
    version: string = "3.0.0-release"
    zoom: number = 1.0

    The scale of the drawing, 1.0 by default: see Zoom, which sets it.

    zoomUpdated: boolean = false
    PageFormatStandards: { [type: string]: PageFormat } = ...

    Standard page format options like A4 or Letter, in portrait and landscape. E.g. PageFormatStandards["A4_P"] or PageFormatStandards["Letter_L"]. One table for all OSMD instances on the page: a format added here, e.g. PageFormatStandards["B5_P"] = new PageFormat(176, 250, "B5_P"), can be used by all of them (setOptions({pageFormat: "B5_P"})). The table itself can't be replaced (readonly).

    • get KeepWarm(): boolean | "auto"

      Whether this instance uses the page's warm keeper: true, false, or "auto" (default): in Chromium-based browsers (Chrome, Edge, Opera, Electron, ...), see isChromiumBrowser(). The keeper is a small rendering OSMD keeps alive so that a sheet rendered after clear() renders about as fast as the one before it. Also the option keepWarm (constructor, setOptions()). The JavaScript engine (V8 in Chrome, Edge and Node) compiles OSMD's code for the objects it creates, and throws that compiled code away once no such object is left, at a full garbage collection. After clear(), nothing of the sheet is left, so the next sheet then rendered up to ~27% slower if such a collection happened in between (Chrome). Firefox and Safari showed no such slowdown, and no gain from the keeper: "auto" makes none there. After the first render() or renderNext() of an instance that uses it, OSMD renders a built-in score of 8 measures (WarmKeeperScore.ts) when the page is idle (requestIdleCallback), into a container that isn't in the page: about 20 ms in Chrome, and a few MB. One keeper per page, shared by the instances that use it, as any rendering keeps the compiled code alive. It's freed when the last of them is disposed (dispose()) or turns this off. Not made without requestIdleCallback (e.g. Node with jsdom).

      Returns boolean | "auto"

    • set KeepWarm(value: boolean | "auto"): void

      Parameters

      • value: boolean | "auto"

      Returns void

    • get Zoom(): number

      The scale of the drawing: 1.0 by default, e.g. 0.5 draws the sheet at half the size, with more measures per system. Call render() after setting it. Like the options, it stays set when another score is loaded (load()) and over clear(), so it can also be set before the first load(). (Up to OSMD 2.3.1, load() and clear() set it back to 1.0.)

      Returns number

    • set Zoom(value: number): void

      Parameters

      • value: number

      Returns void

    • Clears what OSMD has drawn on its canvas, and releases the loaded sheet, so that its memory can be freed while you keep this instance: the sheet's data, its graphical objects and the SVG elements they drew. To show a sheet again, call load() and render(). Until then, the cursors stay hidden, and moving them does nothing. When you don't need the instance anymore, call dispose(), which removes OSMD's listeners on the window.

      Returns void

    • Removes the backends (SVG or canvas) from the container and creates a new one for each page drawn.

      Parameters

      • OptionalpageWidth: number

        the width of the pages in pixels. By default the container's content width, read after removing the backends. An incremental render passes the width all its batches lay the sheet out at (see lazyLayoutWidth).

      Returns void

    • Ends the use of this instance and leaves the container as OSMD found it: does what clear() and dispose() do (releases the sheet, aborts a load() in progress, removes OSMD's listeners and observers), and removes the instance's page elements and cursors from the container. The container's other children stay, e.g. elements of your app. Afterwards load() is rejected and render() throws, with an Error that names destroy(): create a new instance to show a score again, in the same container or another one. Calling destroy() again does nothing.

      Returns void

      // React
      useEffect(() => {
      const osmd = new OpenSheetMusicDisplay(containerRef.current);
      osmd.load(url).then(() => osmd.render()).catch((error) => {
      if (error.name !== "AbortError") { // not an error: destroy() aborted the load
      console.error(error);
      }
      });
      return () => osmd.destroy();
      }, [url]);
    • Removes the listeners OSMD added to the window and the container's reference to this instance, and ends incremental rendering (see renderNext()). Call it when you don't need this instance anymore but keep its container, e.g. to show something else in it: with autoResize (on by default), the container keeps the instance in memory with its loaded and rendered sheet, so that the drawing adapts to the window's size, and a resize would draw the sheet again, replacing the container's content. Without dispose(), an instance is freed together with its container, once the container was removed from the page and your code references neither. Except while incremental rendering on scroll (enableIncrementalRenderingOnScroll()) hasn't drawn the whole sheet: its scroll listener keeps the instance. And in browsers without WeakRef (Chrome before 84, Firefox before 79, Safari before 14.1), the window's resize listener keeps it. A load() that hasn't finished is aborted (see load()). The drawing stays in the container, and the instance stays usable: load() and render() work, and setOptions({autoResize: true}) adds the listeners again. To free the sheet's memory while you keep the instance, call clear(). To remove the instance's elements from the container as well and end its use, call destroy() instead: that is the call for a component's cleanup (e.g. React's useEffect cleanup, Vue's onUnmounted).

      Returns void

      osmd.dispose();
      container.innerHTML = ""; // the instance can be garbage collected now, once your code doesn't reference it anymore
    • Drive renderNext automatically from scrolling: render the next batch whenever the user scrolls within ~1.5 viewports of the not-yet-rendered edge (the page bottom for the endless vertical format, the right edge for RenderSingleHorizontalStaffline). Renders the first batch immediately if none has been rendered yet, then keeps appending as the user scrolls, and detaches itself once all measures are rendered (see renderNext). Re-enabling replaces any previous listener; reset/render/load also detach it.

      Parameters

      • Optionaloptions: IRenderNextOptions & { scrollElement?: Window | HTMLElement }

        batch size (as renderNext) plus an optional scrollElement -- the element whose scrolling drives loading. Defaults to the OSMD container for a single horizontal staffline (it scrolls horizontally) and to window otherwise (the page scrolls vertically).

      Returns void

    • Returns the width in pixels of the container's content box, which the page fills. The page is drawn inside the container's border and padding, so a page as wide as the container's offsetWidth overflowed the container by their width. Like offsetWidth, the width includes a vertical scrollbar of the container. clientWidth doesn't: it would change when createOrRefreshRenderBackend() empties the container and the scrollbar disappears, after render() used it for the layout. It's also 0 in generateImages_browserless, which only sets offsetWidth.

      Returns number

    • Helper function for managing the resize events of autoResize: those of a ResizeObserver on the container, or the window's onResize events in browsers without ResizeObserver (see addResizeListener()). The window keeps its listeners as long as the page is open, so the listener reaches this instance only through a WeakRef: it doesn't keep an instance in memory, with its sheet and drawing, that the app has dropped. Instead, the container keeps the instance until the listener is removed (e.g. by dispose()), so that the drawing adapts to the window's size as long as the container exists, also when the app keeps no reference to the instance, e.g. after const osmd = new OpenSheetMusicDisplay(div); osmd.load(url).then(() => osmd.render()); in a function. In browsers without WeakRef, the listener keeps the instance.

      Parameters

      • startCallback: () => void

        is the function called when resizing starts

      • endCallback: () => void

        is the function called when resizing (kind-of) ends

      Returns void

    • Load a MusicXML file

      Parameters

      • content: string | Blob | Document

        is either the url of a file, or the root node of a MusicXML document, or the string content of a .xml/.mxl file, or a file blob. A string that starts with "<" (after whitespace) is read as XML, also without the XML declaration (). Any other string given here is taken as a URL and requested. That is only done for the string the app passes: what a Blob, an MXL file or the requested URL contains is never requested, it has to be MusicXML (or MXL).

      • tempTitle: string = "Untitled Score"

        is used as the title for the piece if there is no title in the XML. The name or path of a MusicXML file (e.g. "scores/Sonata No. 1.musicxml") is used without its folder and extension. (The options, the EngravingRules and the zoom, osmd.Zoom, stay as they are set when a score is loaded.)

      Returns Promise<{}>

      a promise that is rejected with an Error when the score can't be loaded, for every kind of content: e.g. for malformed XML (the message has the XML parser's line and column), for a file that isn't MusicXML or MXL, or when reading the score fails (the Error's cause is then the reader's error). load() itself doesn't throw. A URL, a Blob and an MXL string are read asynchronously. When load(), clear() or dispose() is called before that has finished, the earlier load() doesn't set the sheet anymore, whichever file arrives first: its request is aborted, and its promise is rejected with an Error whose name is "AbortError" (like an aborted fetch()), so that a .then(() => osmd.render()) of it doesn't run.

      osmd.load(url).then(() => osmd.render()).catch((error) => {
      if (error.name !== "AbortError") { // not an error: another score was loaded meanwhile
      showError(error.message);
      }
      });
    • Render the loaded music sheet to the container. A changed transposition (osmd.Sheet.Transpose, Instrument.Transpose, osmd.TransposeCalculator) or a voice shown or hidden (Voice.Visible, Instrument.Visible) is applied without updateGraphic(): render() creates the graphic again then, see GraphicalMusicSheet.TranspositionChanged and VoiceVisibilityChanged. It does so too when the draw range (drawFromMeasureNumber, drawUpToMeasureNumber) begins or ends inside a multiple rest measure, which is divided there, or one was divided for the previous draw range (see MusicSheetCalculator.multiRestsFitDrawRange()).

      Returns void

    • Re-render and scroll back to previous scroll bar y position in percent. If the document keeps the same height/length, the scroll bar position will basically be unchanged. For example, if you scroll to the bottom of the page, resize by one pixel (or enable dark mode) and call this, for the human eye there will be no detectable scrolling or change in the scroll position at all. If you just call render() instead of renderAndScrollBack(), it will scroll you back to the top of the page, even if you were scrolled to the bottom before.

      Returns void

    • Incrementally render the loaded sheet one batch at a time, appending each batch so a large score paints progressively ("system by system") instead of blocking on a full render(). The first call -- or the first after load(), render() or resetIncrementalRendering() -- starts a fresh session: it clears the container and lays the score out from the first measure to draw. Each later call appends the next batch. Returns progress; once done is true all measures are rendered and further calls are no-ops. A session renders the measures render() draws: the whole sheet, or the range set with the options drawFromMeasureNumber and drawUpToMeasureNumber when the session starts (the progress counts the measures in it). Like render(), a session lays the sheet out at the container's width when it starts: to adapt it to a new width, e.g. after a resize, start a new session. Like render(), it applies a changed transposition (osmd.Sheet.Transpose, Instrument.Transpose, osmd.TransposeCalculator) without updateGraphic(): during a session, the next call then starts it over from its first measure. Page labels are drawn with the batch that finalizes their position: the title block (title, subtitle, composer, lyricist) with the first batch, the copyright (below the last system) with the final batch.

      Pair with enableIncrementalRenderingOnScroll for scroll-to-load, or renderRemaining to finish synchronously (e.g. before PDF/image export). Works for the endless vertical-scroll page format and for RenderSingleHorizontalStaffline (one staffline scrolling right).

      In a container without a width (e.g. a hidden one), no session starts: like render(), the call is skipped with a warning, and returns done: true with 0 measures, so that a loop over the batches ends. With autoResize, render() draws the whole sheet once the container has a width.

      Parameters

      • Optionaloptions: IRenderNextOptions

        batch options; defaults to 8 visual measures (a multi-rest counts as one). Pass systems instead to advance by whole music systems (vertical only); see IRenderNextOptions.

      Returns IRenderNextResult

    • Finish an in-progress incremental render synchronously: render all remaining measures at once. Useful before PDF/image export or printing, which need every system, not just the ones scrolled into view. No-op if no incremental render is in progress, or it is already complete.

      Returns void

    • Releases the loaded sheet and its graphic, and ends incremental rendering: for load(), before it reads the new sheet, and for clear(). The settings stay: the options, the EngravingRules and the zoom.

      Returns void

    • Abandon any in-progress incremental render, so that the next renderNext() starts a new session (with the draw range set then). Called automatically by render(), load() and clear(); call it directly only to cancel a session yourself.

      Returns void

    • Sets the logging level of OSMD: for all OSMD instances on the page, not just this one. It sets the level of OSMD's own loglevel logger (named "OSMD"), not of loglevel's root logger, so the level of the page's other loglevel users stays as it is, and it isn't saved in localStorage (it lasts until the page reloads).

      Until it's called, OSMD logs with the level the root logger has when OSMD loads: warn by default.

      Parameters

      • level: string

        trace, debug, info, warn, error or silent. Any other value logs a warning and sets warn.

      Returns void

    • Set OSMD rendering options using an IOSMDOptions object. Can be called during runtime. Also called by constructor. For example, setOptions({autoResize: false}) will disable autoResize even during runtime. An option that is given is applied, also when it turns something back on (e.g. drawFingerings: true after false); an option that is left out (or undefined) keeps its value. The options object isn't changed. Without an options object (undefined or null), this does nothing but warn.

      Parameters

      Returns void

    • (Re-)creates the graphic sheet from the music sheet, and puts the cursors back to the start. Needed e.g. after changing a rule that applies when the graphic is created, like EngravingRules.RenderHiddenNotes. A changed transposition (osmd.Sheet.Transpose, Instrument.Transpose, osmd.TransposeCalculator) or a voice shown or hidden (Voice.Visible, Instrument.Visible) doesn't need it: render() creates the graphic again then, and keeps the cursors where they are.

      Returns void