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

canvas.toDataURL() turns the canvas’s current pixels into a data: URL, usually a PNG. To save a small image, assign that URL to a download link; to decode an existing data URL, separate its metadata header from its payload and convert the payload into a Blob. For larger exports, use canvas.toBlob() with URL.createObjectURL() to avoid building a large Base64 string in memory. A canvas containing cross-origin pixels without suitable CORS permission cannot be exported.

What canvas.toDataURL() returns

The method serializes the canvas bitmap as a data: URL. By default it requests PNG, and PNG is also the fallback if the browser does not support a requested format. The URL has a header that identifies the media type and, for Base64 data, the encoding; the encoded image follows the comma.

const dataUrl = canvas.toDataURL('image/png');
console.log(dataUrl); // data:image/png;base64,...

You can request a lossy format such as JPEG and pass a quality value from 0 to 1. The quality parameter is relevant to lossy formats; it does not make PNG smaller.

const jpegUrl = canvas.toDataURL('image/jpeg', 0.85);

For formats that support resolution metadata, the exported resolution is 96 dpi. This metadata does not change the bitmap’s pixel dimensions: a 1200-by-800 canvas still contains 1200 by 800 pixels.

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.
#1 Best Overall
Sale
Kodak PIXPRO FZ45 Digital Camera, 16MP Point & Shoot (Black)
  • 16MP Sensor: Captures detailed photos with a CMOS sensor for everyday shooting
  • Optical Zoom: 4x optical zoom with a 27mm wide angle lens for flexible framing indoors or outdoors
  • Full HD Video: Records 1080p video for travel clips, family moments, or simple vlogging
  • Memory Support: Works with Class 10 SD, SDHC, or SDXC cards up to 512GB
  • LCD Screen and Battery: 2.7in LCD screen with 2 AA alkaline batteries for convenient on-the-go use

If the canvas has zero width or height, or exceeds the browser’s maximum canvas size, the result is the special string data:, rather than an image URL.

Download a canvas as an image

For a small export, create an anchor, set its download filename and use the data URL as its href. Run this in response to a user action, such as a button click.

function downloadCanvas(canvas, filename = 'canvas-image.png') {
  const link = document.createElement('a');
  link.download = filename;
  link.href = canvas.toDataURL('image/png');
  link.click();
}

document.querySelector('#download').addEventListener('click', () => {
  downloadCanvas(document.querySelector('canvas'));
});

For JPEG, use canvas.toDataURL('image/jpeg', 0.85) and give the download a .jpg filename. The requested MIME type and filename extension should agree. If you request an unsupported MIME type, the browser can fall back to PNG, so inspect the returned URL’s header when the actual format matters.

Decode a data URL into a Blob

A data URL is not just Base64 text: it begins with a metadata header such as data:image/png;base64,. When decoding one produced by FileReader.readAsDataURL(), or by canvas.toDataURL(), retain the MIME type from the header and decode only the payload after the first comma.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Sale
Kodak PIXPRO FZ55-BK 16MP CMOS Sensor Camera 5X Optical Zoom 28mm Wide
  • 16MP Sensor: Captures detailed photos with a CMOS sensor for everyday shooting
  • Optical Zoom: 5x optical zoom with a 28mm wide angle lens for flexible framing indoors or outdoors
  • Full HD Video: Records 1080p video for travel clips, family moments, or simple vlogging
  • Memory Support: Works with Class 10 SD, SDHC, or SDXC cards up to 512GB
  • LCD Screen and Battery: 2.7in LCD screen and a rechargeable lithium-ion battery for on-the-go use
function dataUrlToBlob(dataUrl) {
  const comma = dataUrl.indexOf(',');
  if (comma === -1) throw new Error('Invalid data URL: missing comma');

  const header = dataUrl.slice(0, comma);
  const payload = dataUrl.slice(comma + 1);
  const mime = /^data:([^;,]+)/i.exec(header)?.[1] || 'application/octet-stream';

  if (/;base64/i.test(header)) {
    const binary = atob(payload);
    const bytes = new Uint8Array(binary.length);
    for (let i = 0; i < binary.length; i++) {
      bytes[i] = binary.charCodeAt(i);
    }
    return new Blob([bytes], { type: mime });
  }

  return new Blob([new TextEncoder().encode(decodeURIComponent(payload))], {
    type: mime
  });
}

const dataUrl = canvas.toDataURL('image/png');
const blob = dataUrlToBlob(dataUrl);
const imageUrl = URL.createObjectURL(blob);

The function handles both Base64 and percent-encoded data URL payloads. atob() returns a binary string, not a JavaScript array of bytes, so each character code is copied into a Uint8Array before creating the Blob. For large canvas exports, avoid this path when possible: toDataURL() first creates the full encoded string in memory.

Blob URLs refer to the in-memory Blob rather than embedding the image bytes in a string. Revoke a URL when it is no longer needed; if the user still needs to view or interact with the image, wait until that interaction is over.

const preview = document.querySelector('#preview');
preview.src = imageUrl;

preview.addEventListener('load', () => {
  // Keep the URL while the preview is in use.
  // Call URL.revokeObjectURL(imageUrl) when you replace or remove it.
}, { once: true });

Use toBlob() for larger images

MDN generally recommends toBlob() with URL.createObjectURL() instead of toDataURL(). It avoids creating a large Base64 string, which can substantially increase memory use for large images. The callback can receive null, so handle that case before creating the URL.

function downloadCanvasBlob(canvas, filename = 'canvas-image.png') {
  canvas.toBlob((blob) => {
    if (!blob) {
      console.error('The browser could not create the image Blob.');
      return;
    }

    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.download = filename;
    link.href = url;
    link.click();

    // Revoke after the download has been initiated.
    setTimeout(() => URL.revokeObjectURL(url), 0);
  }, 'image/png');
}

Pass the desired MIME type as the second argument, for example 'image/jpeg'; a third argument can supply the quality value for lossy output. Keep an object URL alive for as long as a preview or other consumer needs it, and revoke it after that use ends. For the simplest small image export, a data URL remains convenient; for larger output, the Blob route is usually the better fit.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Digital Camera, Latest FHD 1080P Digital Camera for Teens with SD Card Anti Shake Point and Shoot Cameras Portable 16X Zoom Compact Small Cameras for Kids Boys Girls Seniors with Wrist Strap
  • Latest Digital Camera Built-in Fill Light : This compact digital camera is paired with a powerful CMOS processor and image stabilization to help you take & record the most exciting moments in 44 MP quality images & FHD 1080P quality videos anywhere, anytime. Plus, there is also a built-in fill light to help you take high quality pictures even in low light&dark settings, making this the perfect camera for all indoors/outdoors situations.
  • Long-Lasting Battery Life & 16X Digital Zoom :This point and shoot camera will retain its battery charge even after long use. The controls and functions are easy to operate making this the perfect choice for children, teens and younger. This kids camera supports 16x digital zoom, you can zoom in or out the subject by pressing the W/T button for taking still photos to zoom in or out on distant objects and capture all the details you need.
  • Multifunctional & Portable Digital Camera: This cheap digital camera is slim enough to fit in your pocket. You'll easily be able to take it with you on all your indoor/outdoor activities and adventures and ideal for beginners, children and teenagers. This kids digital camera is equipped with 20 filters, anti-shaking, self-timer, continuous shooting, date stamp, time-lapse recording, smile capture, internal MIC and speaker (recording sound videos), great for your daily photography needs.
  • WEBCAM & PAUSE FUNCTION : More than just a FHD 1080p digital camera, it also works as a webcam for video calls and vlogging. Connect the camera to the computer, press shutter and power button at the same time and the camera will automatically turn on webcam mode for all your video calling and live streaming needs. The pause function allows you to pause when seeing playback videos.
  • A Must Have Photography Device : This digital camera with SD card made from high-quality materials, this retro camera is safe and durable. Perfect for all ages to develop & improve their photographic abilities and observation skills. Our dedicated and experienced 24/7 support team is available for all after purchase troubleshooting, questions and technical help.

Why a canvas can be tainted

A canvas is origin-clean only when its pixels can legally be read by the page. Drawing an image or other pixel source from another origin without suitable CORS permission makes the canvas tainted. Calling toDataURL() or otherwise trying to read/export its pixels can then raise a SecurityError.

For an image you load yourself, set its CORS mode before assigning the source, and ensure the remote server sends an appropriate Access-Control-Allow-Origin response header. The remote server must permit your page’s origin; changing client-side code cannot override a server that does not grant access.

const image = new Image();
image.crossOrigin = 'anonymous'; // set before src
image.onload = () => {
  const canvas = document.querySelector('canvas');
  const context = canvas.getContext('2d');
  canvas.width = image.naturalWidth;
  canvas.height = image.naturalHeight;
  context.drawImage(image, 0, 0);

  // This works only if the image response permits CORS.
  const dataUrl = canvas.toDataURL('image/png');
};
image.src = 'https://example.com/image.png';

Using a server-side proxy may be an option only if you control or are authorized to use that service and it fetches the resource safely. Do not treat a proxy as a way to bypass another site’s access controls.

Common errors and fixes

  • The result is data:,. Check that both canvas dimensions are nonzero and within the browser’s maximum canvas size. Reduce the dimensions or export a smaller region if necessary.
  • SecurityError appears during export. The canvas may contain cross-origin pixels. Load the source with CORS enabled and confirm the image server permits your origin, or use content you are entitled to read.
  • The downloaded file is empty or corrupt. Confirm drawing completed before export, verify the canvas dimensions, and check the returned URL begins with an expected image type such as data:image/png;base64,.
  • The decoded bytes are invalid. Do not pass the complete data URL to atob(); split at the first comma and decode only the payload when the header specifies Base64. For a percent-encoded payload, decode it with decodeURIComponent() instead.
  • The file type does not match the requested type. A browser may not support the requested MIME type and can fall back to PNG. Check the data URL or Blob type and use an extension that matches the actual output.
  • The image export uses too much memory. Replace toDataURL() with toBlob() and an object URL, and revoke the URL when its consumer is finished.
  • The download does not start from a delayed callback. Trigger the operation from a clear user action, such as a button click. Browser download handling can restrict downloads that are not associated with user interaction.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If your goal is to capture a webpage rather than export pixels from a canvas already in your app, ScreenshotNeo is a website screenshot API and MCP server. A single GET request returns a PNG, JPEG, WebP, or PDF. For example, save a page as WebP with cURL:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
Kodak PIXPRO FZ55-RD 16MP Camera 5X Optical Zoom 28mm Wide Angle 1080p
  • 16MP Sensor: Captures detailed photos with a CMOS sensor for everyday shooting
  • Optical Zoom: 5x optical zoom with a 28mm wide angle lens for flexible framing indoors or outdoors
  • Full HD Video: Records 1080p video for travel clips, family moments, or simple vlogging
  • Memory Support: Works with Class 10 SD, SDHC, or SDXC cards up to 512GB
  • LCD Screen and Battery: 2.7in LCD screen and a rechargeable lithium-ion battery for on-the-go use
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. Cookie banners are accepted and removed before the shot, along with known newsletter popups and chat widgets; those steps can be turned off. Bot checks, blank pages and failed loads are never billed, and response headers identify page verdict and billing status. Its MCP server lets AI agents use take_screenshot, get_page_info and capture_pdf. The free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000 shots. Sign up for free.

Choose the right export path

Need Use Why
Quickly display or download a small canvas image toDataURL() Returns a directly usable image URL, with no separate Blob URL lifecycle.
Save or preview a large image toBlob() and URL.createObjectURL() Avoids holding the whole Base64-encoded image in a string.
Convert an existing data URL to binary data Parse header and payload, then create a Blob Preserves the MIME type and allows Blob-based downloads or previews.
Export pixels drawn from another origin Make the source CORS-permitted before drawing A tainted canvas cannot be read or exported by client-side code.

Frequently Asked Questions

Does canvas.toDataURL() return only Base64?

No. It returns a complete data: URL, including a media-type and encoding header before the comma-separated payload.

Can toDataURL() export a canvas as JPEG?

Yes. Request image/jpeg and optionally provide a quality value from 0 to 1; the browser can fall back to PNG if the requested type is unsupported.

Does converting a data URL fix a tainted canvas?

No. Converting an already available data URL to a Blob does not grant permission to read cross-origin canvas pixels. The source must be CORS-permitted before drawing.

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

Quick Recap

SaleBestseller No. 1
Kodak PIXPRO FZ45 Digital Camera, 16MP Point & Shoot (Black)
Kodak PIXPRO FZ45 Digital Camera, 16MP Point & Shoot (Black)
16MP Sensor: Captures detailed photos with a CMOS sensor for everyday shooting; Full HD Video: Records 1080p video for travel clips, family moments, or simple vlogging
$99.99
SaleBestseller No. 2
Kodak PIXPRO FZ55-BK 16MP CMOS Sensor Camera 5X Optical Zoom 28mm Wide
Kodak PIXPRO FZ55-BK 16MP CMOS Sensor Camera 5X Optical Zoom 28mm Wide
16MP Sensor: Captures detailed photos with a CMOS sensor for everyday shooting; Full HD Video: Records 1080p video for travel clips, family moments, or simple vlogging
$139.99
Bestseller No. 4
Kodak PIXPRO FZ55-RD 16MP Camera 5X Optical Zoom 28mm Wide Angle 1080p
Kodak PIXPRO FZ55-RD 16MP Camera 5X Optical Zoom 28mm Wide Angle 1080p
16MP Sensor: Captures detailed photos with a CMOS sensor for everyday shooting; Full HD Video: Records 1080p video for travel clips, family moments, or simple vlogging
$139.99

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.