Docs · OSMD 3.0
Rendering in Node.js
OSMD draws into a DOM, and jsdom provides one in Node.js. That’s enough for SVG; for PNG, jsdom draws its canvas with @napi-rs/canvas. No browser, no Puppeteer:
npm install opensheetmusicdisplay jsdom @napi-rs/canvas
// node render.mjs my-score.musicxml my-score.svg (or my-score.png)
import { readFile, writeFile } from 'node:fs/promises';
import { JSDOM } from 'jsdom';
import osmdModule from 'opensheetmusicdisplay';
const { OpenSheetMusicDisplay } = osmdModule; // the package is a CommonJS build
const [input, output] = process.argv.slice(2);
const png = output.endsWith('.png');
// OSMD draws into a DOM: jsdom provides one, @napi-rs/canvas its canvas for PNG.
const { window } = new JSDOM('<!DOCTYPE html><div id="score"></div>');
Object.assign(globalThis, {
window,
document: window.document,
DOMParser: window.DOMParser,
Node: window.Node,
});
const container = window.document.getElementById('score');
// jsdom doesn't lay out pages: tell OSMD how wide the score is, in pixels.
Object.defineProperty(container, 'offsetWidth', { value: 1200 });
const osmd = new OpenSheetMusicDisplay(container, {
autoResize: false,
backend: png ? 'canvas' : 'svg',
});
await osmd.load(await readFile(input, 'utf8'));
osmd.render();
if (png) {
const canvas = container.querySelector('canvas');
const base64 = canvas.toDataURL('image/png').split(',')[1];
await writeFile(output, Buffer.from(base64, 'base64'));
} else {
const svg = container.querySelector('svg');
svg.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
await writeFile(output, svg.outerHTML);
}
node render.mjs my-score.musicxml my-score.svg writes an SVG, … my-score.png a PNG. Our CI runs this script on every change, both ways.
What the script has to do
- Import the package as a whole. The npm package is a CommonJS build, so in Node.js
import { OpenSheetMusicDisplay } from 'opensheetmusicdisplay'fails: take the default export and readOpenSheetMusicDisplayfrom it. Bundlers handle the named import for you. - Give OSMD the browser’s names. It looks for
window,document,DOMParserandNodeas globals. OSMD’s own image generator, which renders the test scores for its visual regression tests, sets a few more (generateImages_browserless.mjs). - Give the element a width. jsdom lays nothing out, so every element is 0 pixels wide. OSMD 3.0 skips a
render()into an element without width; 2.3.1 put one measure on each line.offsetWidthis the width in pixels the score is laid out for. - Leave
autoResizeoff. There’s no window to resize.
Without @napi-rs/canvas, jsdom’s <canvas> is a plain element and the PNG fails, while SVG still works. OSMD’s image generator moved to it with jsdom 31 (pull request 1981), and its PNGs now render like the browser’s.
With pageFormat set (see Options), a score has several pages: one <svg> or <canvas> each, in order.