ScreenshotNeo

BlogHow-to

How to Render Inline SVGs with html2canvas

Render inline SVGs with html2canvas, then troubleshoot missing or mismatched output with practical checks for bounds, resources, and renderer modes.

By the ScreenshotNeo team30 September 202610 min read

How to Render Inline SVGs with html2canvas

To render an inline SVG with html2canvas, keep the <svg> in the DOM subtree you want to capture and pass that element to html2canvas. The project lists SVG as an element it serializes and renders as an image. If the SVG is missing or looks different, check the captured element’s bounds and resource loading, then compare the default renderer with the optional foreignObjectRendering mode in the browsers you support. Neither mode guarantees a pixel-perfect match with the live page.

html2canvas reconstructs an image from DOM information; it is not a native browser screenshot. Its output depends on the library’s implementation of the DOM and CSS features used by your page. The feature list documents inline SVG support, while the FAQ explains why CSS support is selective.

1. Render the inline SVG with the default renderer

Install html2canvas in your frontend project, import it, and call it with the DOM element to capture. The promise resolves to a canvas. This example includes the SVG directly in the captured element so you can confirm the basic path before adding your own page styling.

html2canvas serializes the inline SVG inside the selected DOM subtree and draws it into the output canvas.
html2canvas serializes the inline SVG inside the selected DOM subtree and draws it into the output canvas.
import html2canvas from 'html2canvas';

const target = document.querySelector('#capture');

if (!target) {
  throw new Error('Capture element #capture was not found');
}

html2canvas(target)
  .then((canvas) => {
    document.body.appendChild(canvas);

    // Optional: download the rendered canvas as a PNG.
    const link = document.createElement('a');
    link.download = 'inline-svg.png';
    link.href = canvas.toDataURL('image/png');
    link.click();
  })
  .catch((error) => {
    console.error('html2canvas failed:', error);
  });
<div id="capture">
  <h2>Quarterly result</h2>
  <svg
    xmlns="http://www.w3.org/2000/svg"
    width="160"
    height="100"
    viewBox="0 0 160 100"
    role="img"
    aria-label="Blue circle beside an orange square"
  >
    <circle cx="45" cy="50" r="30" fill="#2563eb" />
    <rect x="85" y="20" width="60" height="60" rx="8" fill="#f97316" />
  </svg>
</div>

Run the JavaScript in a browser after the page and target element exist. The library is browser-side and its getting-started guide describes html2canvas(element, options?) as returning a promise for a canvas. It is not intended for Node.js rendering. See the getting-started guide for installation and basic usage.

Save the result without downloading it

If another part of your application consumes the image, use the returned canvas directly. For example, append it to a preview container or convert it to a Blob for a file upload. A Blob avoids placing a potentially large base64 string in memory as a data URL.

html2canvas(document.querySelector('#capture')).then((canvas) => {
  canvas.toBlob((blob) => {
    if (!blob) {
      console.error('Canvas could not be converted to a PNG blob');
      return;
    }

    const preview = document.querySelector('#preview');
    const image = document.createElement('img');
    image.alt = 'Rendered capture';
    image.src = URL.createObjectURL(blob);
    preview.replaceChildren(image);
  }, 'image/png');
});

2. Check the target and the SVG’s rendered bounds

Before changing renderer settings, make sure the capture includes the SVG and that the browser has laid it out at a visible size. html2canvas serializes the SVG and uses its measured bounds when preparing the serialized representation. This is implementation detail, not a guarantee that every unusual SVG construction will render identically.

  1. Confirm the selector. Check that document.querySelector returns the element you expect. If you pass a parent, verify that it contains the SVG when capture begins.
  2. Inspect dimensions. In developer tools, check the SVG’s bounding rectangle. Its width and height should be greater than zero, and the parent capture element should include those bounds.
  3. Check visibility and clipping. Look for display: none, visibility: hidden, zero opacity, clipping, transforms, overflow rules, or positioning that places the SVG outside the captured area.
  4. Wait for the page state you need. If a framework inserts the SVG after initial rendering, call html2canvas after that update has completed. For animated or changing SVGs, capture at a deliberate point in the animation.
  5. Test a minimal SVG. Replace the complex graphic temporarily with a circle or rectangle. If that renders, add your SVG features back gradually.

Explicit width and height attributes and a suitable viewBox make a useful first diagnostic. They are not a universal requirement, but they make the intended coordinate system and display size easier to inspect.

3. Compare the renderer modes

The normal renderer is the default. The optional foreignObjectRendering configuration asks html2canvas to use a different rendering path where the browser supports ForeignObject drawing. It defaults to false. The project performs feature detection, but browser support and output can vary, so compare the results in the browsers that matter to your application.

html2canvas(document.querySelector('#capture'), {
  foreignObjectRendering: true
}).then((canvas) => {
  document.querySelector('#preview').replaceChildren(canvas);
});

Test both settings against the same DOM and compare whether the SVG appears, whether its styling is close enough for your use, whether dependent resources load, and whether the result is acceptable in each target browser. The configuration documentation describes the option and its default: html2canvas configuration.

Mode When to start What to check
Default (false) For an ordinary first attempt with inline SVG in the DOM. SVG visibility, styling, layout, and any missing features.
foreignObjectRendering: true As a comparison when default output differs from the live page. Browser support, output changes, and whether external resources still load as expected.

Keep the mode that behaves acceptably across your supported browsers. Do not treat ForeignObject as a guaranteed fix: the documentation describes an optional path and feature detection, not a universal SVG compatibility switch.

4. Handle external images, fonts, and origin restrictions

An inline SVG can refer to resources outside its markup, and the surrounding captured element can also contain remote images or backgrounds. Browser origin rules apply to those resources. Setting useCORS: true asks html2canvas to attempt CORS loading; it cannot grant permission that the remote server does not provide. If a remote server does not send suitable CORS headers, the documented alternative is a proxy you control and configure.

html2canvas(document.querySelector('#capture'), {
  useCORS: true,
  onError: (error) => {
    console.error('Resource or rendering issue:', error);
  }
}).then((canvas) => {
  document.querySelector('#preview').replaceChildren(canvas);
});

onError is a notification hook: it can surface resource load or rendering failures while rendering continues. It does not necessarily reject the promise or stop the capture. The configuration reference documents useCORS, proxy, and onError; the FAQ covers cross-origin image behavior.

For a controlled proxy setup, provide the proxy URL in the options and ensure that it can fetch the required resource under your application’s security and access rules:

html2canvas(document.querySelector('#capture'), {
  proxy: 'https://your-domain.example/html2canvas-proxy',
  onError: (error) => console.error(error)
});

The URL above is a placeholder, not an html2canvas service. Implement and secure the proxy for your application; do not expose an unrestricted endpoint that fetches arbitrary URLs. If the SVG and all of its dependencies are inline or same-origin, you may not need CORS or a proxy.

5. Tune scale and other relevant options

Options change how the capture is constructed, but they do not add support for every CSS or SVG feature. Start with the defaults, then change one setting at a time so you can tell which change affects the result.

Option Documented default Use
foreignObjectRendering false Compare the optional ForeignObject path when the ordinary renderer produces different output.
useCORS false Attempt CORS loading for remote images; the server must allow it.
proxy null Route eligible resource loading through an application-managed proxy.
scale Device pixel ratio Control output pixel density. Higher values produce larger canvases and use more memory.
onError No callback Receive notifications about resource load or rendering failures while rendering continues.

For example, use a lower scale when the output is too large for a preview or downstream upload:

html2canvas(document.querySelector('#capture'), {
  scale: 1,
  useCORS: true,
  onError: (error) => console.warn('Capture warning:', error)
});

The rendered pixel dimensions are related to the element’s layout size and the selected scale. Large full-page or high-scale captures can consume substantial browser memory. Choose a scale that meets the output’s actual display or export needs, and avoid repeatedly retaining canvases and object URLs you no longer use.

6. Troubleshoot missing or incorrect SVG output

Use this order to narrow down the cause without changing several variables at once.

  1. Verify the target and geometry. Confirm the correct element is passed in, the SVG exists at capture time, its measured width and height are nonzero, and the target bounds include it.
  2. Inspect console and debug output. Look for resource errors and enable the documented logging option if useful. Add onError to see reported failures; remember that rendering may continue after a notification.
  3. Check resource origin and response headers. Identify images, CSS backgrounds, fonts, or other resources referenced by the page or SVG. Try useCORS: true only when the server permits cross-origin access; otherwise configure a proxy.
  4. Compare renderer modes. Capture once with defaults and once with foreignObjectRendering: true in each relevant browser. Record which feature differs instead of assuming one mode wins everywhere.
  5. Reduce to a reproduction. Remove unrelated page content and SVG features until the missing output can be reproduced in a small case. Then add features back one at a time.
Symptom Likely cause Next step
The entire SVG is absent The capture target excludes it, it has no visible bounds, or it is inserted after capture starts. Check the selector, bounding rectangles, visibility, and capture timing.
SVG appears but an embedded image is missing The image failed to load or is blocked by origin policy. Inspect errors and network requests; configure valid CORS or a controlled proxy.
Appearance differs from the browser A styling or SVG feature is not reproduced the same way by the selected rendering path. Compare modes, isolate the feature, and check the project’s feature list and FAQ.
Some CSS is missing or partial html2canvas implements CSS properties selectively. Check the FAQ, simplify the style, and create a minimal reproduction for unsupported behavior.
Output is unexpectedly large or slow The target is large or scale is high, increasing canvas pixel count and memory use. Capture a smaller target or lower scale to the required output resolution.

The project FAQ explains that CSS properties must be implemented individually and that full CSS support is not a goal. That means an SVG can be supported as an element while a particular CSS effect applied to it still differs. The FAQ suggests reducing a missing or partial CSS case to a test case; a single issue report such as “SVG elements not present in output” is evidence of a reported case, not a general compatibility verdict.

7. Performance, reliability, and output expectations

Rendering happens in the browser and depends on the page state and resources available to that browser. Wait until the content you want is present, avoid needlessly capturing a much larger subtree, and set scale deliberately. A canvas with many pixels can increase memory pressure, particularly when your code retains multiple captures or converts them to data URLs.

A URL screenshot service can capture a rendered page without requiring an html2canvas call inside your own DOM.
A URL screenshot service can capture a rendered page without requiring an html2canvas call inside your own DOM.

For reliability, handle both promise rejection and resource notifications. A successful promise does not prove that every image or style rendered as intended; inspect the resulting output in the browsers you support. Keep the capture inputs stable during rendering, especially if the page includes animation, transitions, or content that updates asynchronously.

There is no per-capture service price for html2canvas itself described in the cited project documentation: it is a browser library. Your practical costs are the development and maintenance required to handle browser differences, resources, output sizes, and the fidelity your use case requires. The library’s own FAQ is explicit that it does not aim for full CSS support, so use it where reconstructed DOM output is suitable rather than assuming it will equal a native screenshot.

8. Or skip the browser setup

If you need a screenshot of a URL rather than a canvas generated inside your own page, ScreenshotNeo is a website screenshot API and MCP server. Its API returns an image or PDF from one GET request. For a URL that contains an inline SVG, the capture is of the rendered page in the browser service; this is a different workflow from calling html2canvas on your own DOM subtree.

See the ScreenshotNeo API docs for request options. A minimal cURL call is:

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

ScreenshotNeo removes cookie and consent banners, newsletter popups, and chat widgets before capture; each cleanup step can be turned off. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed, and responses identify the page verdict and billing status in headers. Its MCP server provides take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients. The free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 shots.

Sign up for ScreenshotNeo’s free plan to get 1,000 screenshots a month with no card.

9. Frequently asked questions

Does html2canvas support inline SVG?

Yes. Its feature list includes <svg> as an element that is serialized and rendered as an image. Particular SVG features, styles, or external resources can still produce different results.

Should I always enable foreignObjectRendering?

No. It is optional and defaults to off. Compare it with the default renderer in the browsers you support when you have a concrete output difference to investigate.

Can I run html2canvas in Node.js?

The getting-started documentation describes html2canvas as a browser-side library and says it is not suitable for Node.js. Use it in a browser context.

Why does a screenshot differ from what I see on screen?

html2canvas reconstructs the page from DOM information rather than taking a native browser screenshot. Its rendering support is selective, especially for CSS, so inspect the relevant feature and reduce the case to a reproduction.