Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
JavaScript

How to Convert Mermaid Diagrams to PNG with JavaScript

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Mermaid’s JavaScript API renders diagram definitions as SVG, not as PNG bytes. To create a PNG, first render the definition with Mermaid, then load the resulting SVG into an image and draw it onto a canvas. The example below does both in a browser and downloads the result.

How Mermaid-to-PNG conversion works

The conversion has two distinct stages: Mermaid parses your diagram text and generates SVG markup; a browser then rasterizes that SVG into pixels. This distinction matters because mermaid.render() returns SVG, not a PNG file or PNG byte stream. You need an additional image-rendering step to produce PNG.

PNG is useful for presentations, documents, and other destinations that expect a raster image. SVG remains sharp when resized and is often a better choice for web pages, print, or large-format output. If your destination accepts SVG and you need to resize the diagram substantially, keep the SVG rather than converting it just to convert it back later.

Prerequisites and version notes

For a browser project, install Mermaid as a dependency with npm install mermaid (or the equivalent Yarn or pnpm command), then bundle the code with your application. Mermaid’s current usage documentation specifies Node.js 22.12.0 or later for npm-package usage. That requirement is for the package workflow, not a claim that a browser itself runs on Node.js. Mermaid v12.0.0 and later target ES2024; the documentation aims to support Safari 17.4 or later and reports linting for Chromium 121 and Firefox 123, while explicitly making no support commitment for those older Chromium and Firefox versions. Check the current Mermaid compatibility documentation for the runtime and browser versions you intend to support, since these details can change.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The example assumes a modern browser with ES-module support, SVG image loading, and canvas. Run it from a local development server or your application rather than relying on opening an arbitrary local file directly; browser module and download behavior can differ by setup.

Runnable browser example

This page takes Mermaid text, validates it, renders SVG, draws the SVG to a canvas, and downloads a PNG. It uses Mermaid’s asynchronous render API rather than the deprecated mermaid.init pattern. Save the following as part of a page bundled with Mermaid installed:

import mermaid from 'mermaid';

mermaid.initialize({
  startOnLoad: false,
  securityLevel: 'strict',
});

const definition = `flowchart TD
  A[Write Mermaid] --> B[Render SVG]
  B --> C[Rasterize to PNG]
`;

const button = document.querySelector('#download');
const status = document.querySelector('#status');

button.addEventListener('click', async () => {
  button.disabled = true;
  status.textContent = 'Rendering…';

  try {
    // Optional but useful when you want syntax errors before rendering.
    const parsed = await mermaid.parse(definition);
    if (!parsed) throw new Error('Mermaid did not accept the definition.');

    const { svg } = await mermaid.render('diagram-for-png', definition);
    const pngBlob = await svgToPng(svg, { scale: 2, background: '#ffffff' });

    const downloadUrl = URL.createObjectURL(pngBlob);
    const link = document.createElement('a');
    link.href = downloadUrl;
    link.download = 'diagram.png';
    link.click();
    URL.revokeObjectURL(downloadUrl);

    status.textContent = 'PNG downloaded.';
  } catch (error) {
    console.error(error);
    status.textContent = `Could not create PNG: ${error.message}`;
  } finally {
    button.disabled = false;
  }
});

async function svgToPng(svg, { scale = 1, background = null } = {}) {
  const svgBlob = new Blob([svg], {
    type: 'image/svg+xml;charset=utf-8',
  });
  const svgUrl = URL.createObjectURL(svgBlob);
  const image = new Image();

  try {
    image.src = svgUrl;
    await image.decode();

    const width = image.naturalWidth;
    const height = image.naturalHeight;
    if (!width || !height) throw new Error('The rendered SVG has no usable dimensions.');

    const canvas = document.createElement('canvas');
    canvas.width = Math.ceil(width * scale);
    canvas.height = Math.ceil(height * scale);
    const context = canvas.getContext('2d');
    if (!context) throw new Error('Canvas 2D is unavailable in this browser.');

    if (background !== null) {
      context.fillStyle = background;
      context.fillRect(0, 0, canvas.width, canvas.height);
    }
    context.drawImage(image, 0, 0, canvas.width, canvas.height);

    return await new Promise((resolve, reject) => {
      canvas.toBlob(blob => {
        if (blob) resolve(blob);
        else reject(new Error('The browser could not encode a PNG.'));
      }, 'image/png');
    });
  } finally {
    URL.revokeObjectURL(svgUrl);
  }
}

The sample assumes these controls exist in your page:

<button id="download" type="button">Download PNG</button>
<p id="status" role="status"></p>

For this example, scale: 2 requests a canvas twice the SVG’s intrinsic width and height. That increases the output pixel dimensions in both directions, so the PNG has four times as many pixels as a scale-1 image and may use more memory and disk space. Use scale: 1 for the SVG’s intrinsic size, or choose a larger scale when the image needs to look sharp at a larger display size.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Validate, render, and preserve interactions

Check syntax before rendering

Use mermaid.parse(definition) when you want a separate validation step or want to show a more specific error before rasterization. Mermaid’s usage documentation describes its return value as { diagramType: string } when the text follows Mermaid syntax. Invalid syntax throws by default unless error suppression is configured, so catch errors at the boundary of your UI or job rather than letting a rejected promise go unhandled.

Render to SVG and insert it when needed

mermaid.render(id, definition) is asynchronous and returns an SVG string. The result can also include a bindFunctions function for diagrams with interactions. If your output needs those interactions, insert the returned SVG into the DOM and then call bindFunctions on the inserted element. A PNG is a static bitmap: it preserves the diagram’s appearance, not clickable or other interactive behavior.

The download example does not insert SVG into the page or invoke event bindings because its goal is a static image. If you also want a live diagram preview, insert the SVG in a preview container, then call the optional binding function after insertion. For rendering Mermaid elements already present in a page, the current guide recommends mermaid.run; mermaid.init has been deprecated since Mermaid v10.

Choose dimensions and background deliberately

The SVG’s dimensions determine the starting canvas size in the example; the scale factor multiplies those dimensions. If you need a specific output width and height, decide whether to preserve the aspect ratio and calculate the other dimension accordingly. Stretching the diagram to unrelated dimensions can distort node shapes and text. Very large canvases can also consume substantial browser memory, so use a practical output size rather than scaling without limit.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • White or another solid background: pass a color such as '#ffffff'. The sample fills the canvas before drawing the SVG.
  • Transparent background: pass null. Do not fill the canvas; PNG supports transparency. The diagram’s own rendered shapes or theme may still have fills.
  • Theme-based appearance: set Mermaid’s theme and diagram styling in the Mermaid rendering configuration or definition, then rasterize the returned SVG. Mermaid Chart’s export guidance says to put the theme in diagram front matter when its editor-level preferences do not carry through to exports; that advice describes Mermaid Chart’s export workflow, not every custom JavaScript renderer.
  • Pixelated output: increase the raster scale or use SVG if the destination supports it. Larger PNG dimensions generally mean a larger file.

Fonts, SVG content, and security

Wait for fonts before rendering

Font availability affects text metrics and layout. Mermaid warns that rendering before dynamically loaded fonts finish can leave labels out of bounds. If your app loads web fonts, wait for them before calling mermaid.render—for example, await document.fonts.ready—and ensure the font is available in the rendering page. Test the final image in the browser versions your app supports; font fallback and SVG image behavior can affect the result.

Keep untrusted definitions in strict mode

Mermaid documents strict as its default security level: HTML tags in text are encoded and click functionality is disabled. Treat user-supplied definitions as untrusted input and do not loosen security settings merely to make a diagram more interactive. Mermaid’s sandbox mode renders in a sandboxed iframe, and some interactive features may be restricted. Choose the mode to match your threat model and the behavior your application actually needs.

Account for the browser’s SVG-to-canvas path

The sample creates a local SVG Blob URL and asks the browser to decode it as an image before drawing it. Browser handling of SVG features, fonts, and image content can vary. If drawing or PNG encoding fails, reduce the diagram to a minimal case and check whether the SVG contains content your target browser cannot rasterize as expected. Avoid assuming that any SVG string can be drawn identically in every runtime.

Node.js and other rendering environments

Mermaid’s render API is useful in a browser, but the conversion step depends on an environment that can rasterize SVG. The browser sample uses Image, canvas, and toBlob; those are browser APIs, not a portable Node.js PNG encoder. In Node, you must choose and configure an SVG-capable rendering environment or another tool that can produce raster output, then verify its font loading, SVG feature support, dimensions, and output behavior. The Mermaid documentation’s Node.js package requirement does not by itself provide that rasterization layer.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For server-side rendering, make the renderer part of your application’s deployment and test it with the same Mermaid definitions, fonts, and runtime versions used in production. Do not copy browser canvas code into a Node process and expect it to work unchanged. If a project needs a specific Node implementation, select a maintained rendering library or browser automation environment based on its documented support for your Node version and the SVG features in your diagrams.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Common problems and fixes

  • “I can’t get PNG from mermaid.render.” Its result is SVG markup, not PNG bytes. Add a rasterization step such as loading the SVG into an image and drawing it on a canvas.
  • The definition fails to render. Call mermaid.parse and catch its error. Check Mermaid syntax, including diagram-specific punctuation and indentation, before debugging the canvas stage.
  • The output is blank or has zero dimensions. Wait for the SVG image to decode, then check its intrinsic dimensions. Ensure you pass the SVG string returned by Mermaid rather than a DOM node or an empty value.
  • Labels are clipped or positioned unexpectedly. Wait for web fonts to load before rendering; Mermaid notes that late font loading can change text layout.
  • The PNG is blurry. Increase the scale used for canvas dimensions, or keep SVG if the destination can display vector files.
  • The PNG is unexpectedly opaque. The example fills a white background. Pass null to leave the canvas transparent, and check whether the Mermaid theme or diagram elements themselves have opaque fills.
  • Canvas encoding returns no file. Check the browser console and the SVG image-loading result. The sample rejects if toBlob does not return a Blob; test a smaller diagram and check browser support and SVG content.
  • Interactions disappear. That is expected for a static PNG. For an interactive preview, insert the SVG into the DOM and call its optional bindFunctions afterward.

Or skip the browser setup

ScreenshotNeo is a website screenshot API and MCP server, not a direct Mermaid-definition-to-PNG converter. It fits when your Mermaid diagram is already rendered on a web page and you want a screenshot of that page; this browser code remains the direct route from Mermaid text to a PNG file. One GET request captures a URL:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

See the ScreenshotNeo API documentation for request options. ScreenshotNeo removes cookie banners, newsletter popups, and chat widgets before capture; bot checks, blank pages, and failed loads are never billed. Its MCP server lets AI agents use tools to take screenshots. The Free plan includes 1,000 screenshots a month with no card, and paid plans start at $5 for 3,000 shots. Learn about ScreenshotNeo, or sign up for 1,000 free screenshots a month with no card.

When to use PNG, and when to keep SVG

Use PNG when a presentation, document, or sharing workflow requires an image file and you can choose a suitable pixel size. Keep SVG when the destination accepts vector graphics and crisp scaling matters. For a static share image, Mermaid’s output can be rasterized as shown above; for a diagram that must remain interactive, serve or display SVG in the page instead of treating PNG as an equivalent.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Frequently Asked Questions

Does Mermaid’s render API return PNG data?

No. It returns SVG markup; a browser or another rendering environment must rasterize it to create PNG.

Can a PNG preserve clickable Mermaid nodes?

No. PNG is static. Use the inserted SVG and its optional event bindings if you need interactions.

Why do fonts change the exported diagram?

Font availability changes text measurements and can affect layout. Wait for dynamically loaded fonts before rendering.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Read next

Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.