ScreenshotNeo

BlogHow-to

How to Render a Nuxt Page as an Image with html-to-image

Capture a Nuxt component in the browser with html-to-image, download PNG, JPEG, SVG or Blob output, and troubleshoot fonts, assets and canvas issues.

By the ScreenshotNeo team30 September 20269 min read

How to Render a Nuxt Page as an Image with html-to-image

Direct answer: install html-to-image, attach a Vue template ref to the element you want to export, and call toPng(element) from a browser-only event handler. The function returns a promise containing a PNG data URL that you can display or download. Because Nuxt renders universal applications on both the server and browser, keep DOM-dependent imports and capture calls in client-side code.

html-to-image captures a DOM node. It does not accept a Nuxt route or URL. Choose the exact rendered element whose contents should appear in the image.

What you will build

The example below renders a card, waits until it exists in the browser, converts it to PNG, and downloads it as nuxt-page.png. It also reports failures in the interface.

Install html-to-image

npm install html-to-image

See the html-to-image README for the documented API and options.

html-to-image clones a selected DOM node and produces several browser-side output formats.
html-to-image clones a selected DOM node and produces several browser-side output formats.

Basic Nuxt component

Create a component such as components/ImageExport.vue:

<script setup lang="ts">
import { ref } from 'vue'
import { toPng } from 'html-to-image'

const captureTarget = ref<HTMLElement | null>(null)
const errorMessage = ref('')
const isExporting = ref(false)

async function downloadImage() {
  if (!captureTarget.value || isExporting.value) return

  isExporting.value = true
  errorMessage.value = ''

  try {
    const dataUrl = await toPng(captureTarget.value)
    const link = document.createElement('a')
    link.download = 'nuxt-page.png'
    link.href = dataUrl
    link.click()
  } catch (error) {
    console.error(error)
    errorMessage.value = 'The image could not be generated. Check the asset and canvas troubleshooting steps below.'
  } finally {
    isExporting.value = false
  }
}
</script>

<template>
  <section>
    <div ref="captureTarget" class="export-card">
      <h1>Nuxt report</h1>
      <p>This rendered component will become an image.</p>
      <div class="metric">42%</div>
    </div>

    <button type="button" :disabled="isExporting" @click="downloadImage">
      {{ isExporting ? 'Creating image…' : 'Download PNG' }}
    </button>
    <p v-if="errorMessage" role="alert">{{ errorMessage }}</p>
  </section>
</template>

The ref is nullable because the element does not exist until Vue has rendered it. The click handler runs after hydration, so document and the DOM node are available. Do not call toPng during server rendering.

Using ClientOnly in Nuxt

If the component or its import relies on browser APIs or side effects, wrap the capture UI in Nuxt’s <ClientOnly> boundary:

<template>
  <ClientOnly fallback="Loading export controls…">
    <ImageExport />
  </ClientOnly>
</template>

Obtain the ref after the client-only content exists. A button click after rendering is a natural capture point. Nuxt’s rendering guidance explains the universal/server-and-browser model and client-only boundaries: Nuxt rendering documentation.

Do not switch the entire application to ssr: false just to support one export button unless the application is intentionally client-rendered. That changes the rendering model for every route.

Wait for fonts, images and async content

Capture after the target has rendered and its important assets have loaded. For an explicit button this usually happens naturally, but dashboards and image-heavy cards may still be loading.

async function waitForCaptureAssets(node: HTMLElement) {
  if (document.fonts?.ready) {
    await document.fonts.ready
  }

  const images = Array.from(node.querySelectorAll('img'))
  await Promise.all(images.map((image) => {
    if (image.complete) return Promise.resolve()
    return new Promise<void>((resolve) => {
      image.addEventListener('load', () => resolve(), { once: true })
      image.addEventListener('error', () => resolve(), { once: true })
    })
  }))
}

async function downloadImage() {
  const node = captureTarget.value
  if (!node) return

  await waitForCaptureAssets(node)
  const dataUrl = await toPng(node)
  const link = document.createElement('a')
  link.download = 'nuxt-page.png'
  link.href = dataUrl
  link.click()
}

An image that fails to load can leave a blank region. The library documents an image placeholder option for failed image fetches; use it when a fallback graphic is acceptable.

Output formats

Function Result Use it when
toPng(node) PNG data URL You need lossless output or a direct <img src> or download.
toJpeg(node, options) JPEG data URL You want smaller photographic output. The documented quality range is 0 to 1 and defaults to 1.
toBlob(node) Blob You need file APIs, uploads, or object URLs instead of a large data URL.
toSvg(node) SVG data URL You need the serialized SVG representation.
toCanvas(node) Canvas You need to draw, inspect or further process the canvas.
toPixelData(node) Pixel bytes You need raw pixel processing.

JPEG download

import { toJpeg } from 'html-to-image'

const dataUrl = await toJpeg(captureTarget.value!, {
  quality: 0.85,
  backgroundColor: '#ffffff'
})

const link = document.createElement('a')
link.download = 'nuxt-page.jpg'
link.href = dataUrl
link.click()

JPEG has no transparency. Set a background color when the source design depends on a transparent page background.

Blob download and upload

import { toBlob } from 'html-to-image'

const blob = await toBlob(captureTarget.value!)
if (!blob) throw new Error('No image blob was produced')

const objectUrl = URL.createObjectURL(blob)
const link = document.createElement('a')
link.download = 'nuxt-page.png'
link.href = objectUrl
link.click()
URL.revokeObjectURL(objectUrl)

const form = new FormData()
form.append('file', blob, 'nuxt-page.png')
await fetch('/api/upload', { method: 'POST', body: form })

Useful html-to-image options

The library clones the DOM, copies computed styles, recreates pseudo-elements, embeds fonts and images, serializes the result through SVG foreignObject, and rasterizes it when you request PNG or JPEG. Options let you control the resulting image:

  • backgroundColor: fill transparent areas.
  • width and height: override the cloned node dimensions.
  • canvasWidth and canvasHeight: control raster canvas dimensions.
  • style: apply temporary style overrides to the cloned node.
  • filter: exclude nodes from the capture.
  • pixelRatio: increase or reduce output density.
  • imagePlaceholder: provide a fallback for images that cannot be fetched.
  • Font embedding controls: tune how external fonts are included.

Exclude a node

const dataUrl = await toPng(captureTarget.value!, {
  filter: (node) => !(node instanceof HTMLElement && node.dataset.exportIgnore === 'true')
})
<button data-export-ignore="true" type="button">Live controls</button>

Export at a larger pixel size

const dataUrl = await toPng(captureTarget.value!, {
  pixelRatio: 2
})

Higher dimensions and pixel ratios increase memory use, conversion time and output size. Capture only the component you need rather than an entire long page.

Capture a specific page section

Put the ref on the section, card or component that should appear in the image. A ref on <body> or a layout wrapper may include navigation, transient controls and unrelated content.

<div ref="captureTarget" class="invoice-card">
  <InvoiceSummary :invoice="invoice" />
</div>

If the visual is generated asynchronously, render a loading state until its data, fonts and images are ready, then enable the export button.

How the capture works

The conversion is client-side. The library recursively clones the selected DOM subtree, copies computed CSS, recreates pseudo-elements, embeds assets, serializes the clone to SVG with foreignObject, and uses an image and off-screen canvas for raster formats. This explains why external assets, browser support, canvas provenance and very large DOM trees affect success.

Troubleshooting

Symptom Likely cause Fix
window is not defined or import failure during build DOM-dependent code ran during Nuxt server rendering. Call capture from a client event handler; use <ClientOnly> where needed. Keep universal rendering enabled unless the whole app is intentionally client-rendered.
The ref is null The element has not rendered, or the component is conditionally hidden. Capture after mount or from a click after the element is visible. Check the ref before calling the library.
Images are blank An image request failed, is still loading, or cannot be embedded. Wait for image completion, verify the URL, use imagePlaceholder, and inspect cross-origin restrictions.
Custom fonts are missing Fonts were not loaded before cloning or cannot be fetched for embedding. Await document.fonts.ready, verify font URLs and test the actual production font configuration.
Security or tainted-canvas error An embedded canvas contains pixels from an origin that does not permit the required access. Use same-origin or correctly configured cross-origin assets, or remove the tainted canvas from the capture.
Output is clipped The target or canvas dimensions do not include the intended content. Capture the correct wrapper and set documented width, height, canvasWidth or canvasHeight values deliberately.
Browser throws a data URL or memory error The DOM tree or pixel dimensions are too large. Capture a smaller element, lower pixelRatio, reduce dimensions, or use toBlob for file-oriented handling.
Pseudo-elements or CSS backgrounds differ Computed-style cloning does not reproduce every browser or asset condition identically. Test the real component, make required assets fetchable, and simplify export-only styling when exact fidelity matters.
Safari, Firefox or an older browser fails The conversion relies on Promise and SVG foreignObject support. Use a current supported browser and provide a server-side or downloadable fallback when your audience includes unsupported browsers.

Performance and reliability checklist

  • Capture the smallest meaningful subtree.
  • Wait for fonts, images and async data before starting.
  • Use PNG for sharp UI and transparency; use JPEG when photographic compression is more useful.
  • Use a moderate pixelRatio; a larger value is not free in memory or file size.
  • Prefer toBlob when uploading or processing files.
  • Disable the export button while a conversion is running to prevent duplicate work.
  • Catch and display rejected promises; a browser capture can fail for asset, canvas, memory or support reasons.
  • Test production asset URLs, not only local development URLs.
  • Do not assume a screenshot of a very long route will fit browser data URL limits.

When a browser capture is the wrong tool

html-to-image is appropriate when the user is already viewing a rendered component and needs a client-side export. It is less suitable when you need scheduled captures, screenshots of URLs that are not open in the user’s browser, consistent automation across pages, or a service that handles consent banners and failed loads before billing.

ScreenshotNeo removes common consent banners, popups and chat widgets before capture.
ScreenshotNeo removes common consent banners, popups and chat widgets before capture.

Or skip the browser setup

ScreenshotNeo provides a website screenshot API and MCP server. One GET request returns a PNG, JPEG, WebP or PDF for a URL. It can accept cookie and consent banners as a visitor and remove more than 60 known consent platforms, newsletter popups and chat widgets before capture; each cleanup step can be turned off. Bot checks and CAPTCHAs, blank pages, timeouts, failed loads and cache hits are not billed, and the response identifies the result with X-Page-Verdict and X-Billed headers.

For a deployed Nuxt page, use the API documented at ScreenshotNeo docs:

cURL

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

Python

import requests

r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://example.com/nuxt-page"}, timeout=90)
open("shot.webp", "wb").write(r.content)

Node.js

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://example.com/nuxt-page' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

ScreenshotNeo also supports full-page capture with lazy images loaded, element capture by CSS selector, dark mode, device presets and custom viewports, retina scale, custom CSS and JavaScript, waits, request blocking, headers, cookies, user agents, authorization, timezone, geolocation, transparent backgrounds, resizing, caching, signed links, asynchronous jobs, webhooks, bulk capture and a usage API. Its MCP server exposes take_screenshot, get_page_info and capture_pdf 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; every feature is available on every plan. Create a free ScreenshotNeo account.

FAQ

Can html-to-image capture a Nuxt route directly?

No. It receives a DOM node. Navigate to or render the route in the browser, then pass the element referenced by Vue’s template ref.

Should I use toPng or toJpeg?

Use PNG for UI, text and transparency. Use JPEG when a smaller, lossy image is acceptable and choose a quality value from 0 to 1.

Can I export an entire long page?

You can target a large wrapper, but very large DOMs and data URLs can fail. A focused component is more reliable; reduce dimensions or pixel ratio when necessary.

Why does the output differ from the visible page?

The library reconstructs the node and embeds assets rather than taking a compositor-level browser screenshot. Fonts, cross-origin images, pseudo-elements, canvases and browser support can change the result.

Do I need to disable Nuxt SSR?

No. Keep universal rendering and run the export interaction in the browser. Use <ClientOnly> for browser-dependent UI when appropriate.