What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

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

To convert an SVG shown in an HTML page into a PNG, load the SVG as an image, draw it onto a canvas at the pixel dimensions you want, and export the canvas with toBlob(). Wait for the image to load first, preserve its aspect ratio, and make sure any cross-origin images inside the SVG are allowed by CORS.

Convert an SVG to a downloadable PNG in the browser

This method rasterizes the SVG into canvas pixels, then encodes those pixels as a PNG. It works with a URL that the browser can load as an image. The output dimensions are the canvas dimensions, not necessarily the SVG’s displayed size in the page layout.

async function svgToPngBlob(svgUrl, width, height) {
  const image = new Image();
  image.src = svgUrl;
  await image.decode();

  const canvas = document.createElement("canvas");
  canvas.width = width;
  canvas.height = height;

  const context = canvas.getContext("2d");
  if (!context) {
    throw new Error("Could not create a 2D canvas context");
  }

  context.drawImage(image, 0, 0, width, height);

  return new Promise((resolve, reject) => {
    canvas.toBlob((blob) => {
      if (blob) {
        resolve(blob);
      } else {
        reject(new Error("PNG encoding failed"));
      }
    }, "image/png");
  });
}

async function downloadSvgAsPng() {
  const blob = await svgToPngBlob("/images/logo.svg", 1200, 600);
  const objectUrl = URL.createObjectURL(blob);
  const link = document.createElement("a");
  link.href = objectUrl;
  link.download = "logo.png";
  link.click();
  link.remove();
  URL.revokeObjectURL(objectUrl);
}

 downloadSvgAsPng().catch(console.error);

Replace /images/logo.svg with the SVG’s same-origin URL and choose the output width and height. The example uses a 2:1 canvas; if the source has a different aspect ratio, change those values to match it or the image will be stretched. MDN Web Docs describes toBlob() as creating a Blob object representing the image contained in a canvas.

Why the image must load first

drawImage() needs a decoded image. await image.decode() resolves when the image is ready for use and rejects if it cannot be decoded. An alternative is to attach load and error handlers before assigning src; do not draw immediately after setting src, because network loading may still be in progress.

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

Choose output dimensions deliberately

Canvas width and height determine the PNG’s pixel dimensions. To calculate a proportional height, use the SVG’s aspect ratio: height = width × sourceHeight ÷ sourceWidth. For example, a 400-by-200 SVG rendered at 1200 pixels wide should be exported at 600 pixels high. If you need a sharper bitmap, increase both dimensions by the same scale factor; the resulting file will contain more pixels, but also use more memory and generally take longer to encode.

An SVG may have a viewBox but no root width and height. For the image-loading workflow, MDN’s canvas image guidance says the root SVG should specify both dimensions. Add suitable dimensions to the SVG source when you control it. A page’s CSS sizing does not automatically define the desired exported pixel dimensions.

Download a PNG from an SVG already in the page

If the SVG is inline in the HTML rather than referenced by a URL, serialize the SVG element into a string, make it into an SVG Blob URL, and load that URL as an image before drawing it to canvas. The serialized SVG needs explicit root dimensions to provide predictable output.

async function inlineSvgToPngBlob(svgElement, width, height) {
  const clone = svgElement.cloneNode(true);
  clone.setAttribute("width", String(width));
  clone.setAttribute("height", String(height));

  const svgText = new XMLSerializer().serializeToString(clone);
  const svgBlob = new Blob([svgText], {
    type: "image/svg+xml;charset=utf-8"
  });
  const svgUrl = URL.createObjectURL(svgBlob);

  try {
    return await svgToPngBlob(svgUrl, width, height);
  } finally {
    URL.revokeObjectURL(svgUrl);
  }
}

async function downloadInlineSvg() {
  const svg = document.querySelector("svg#diagram");
  if (!svg) throw new Error("SVG element #diagram was not found");

  const pngBlob = await inlineSvgToPngBlob(svg, 1000, 700);
  const pngUrl = URL.createObjectURL(pngBlob);
  const link = document.createElement("a");
  link.href = pngUrl;
  link.download = "diagram.png";
  link.click();
  link.remove();
  URL.revokeObjectURL(pngUrl);
}

downloadInlineSvg().catch(console.error);

In this example the helper from the previous section is reused. Keep the width-to-height ratio consistent with the SVG’s viewBox if you want to avoid distortion. If the SVG contains linked images, fonts, or other external resources, those dependencies may not render as expected in the image context; inline them where practical and verify the result.

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

Use toDataURL() when you need a data URI

For a compact example or an interface that specifically needs a data URI, serialize the canvas with toDataURL("image/png") instead of using toBlob(). PNG is the default canvas image format and is required by browsers. A data URI is a base64-encoded string, which can become large for high-resolution images; a Blob is usually a better fit for a downloadable file or upload.

const pngDataUrl = canvas.toDataURL("image/png");
const link = document.createElement("a");
link.href = pngDataUrl;
link.download = "image.png";
link.click();

MDN notes that formats supporting resolution metadata are written at 96 dpi. That metadata does not change the canvas’s pixel dimensions; set those dimensions explicitly for the bitmap you need.

Handle CORS and external SVG resources

A canvas becomes tainted if it includes pixels from cross-origin content that was loaded without the required CORS approval. Once tainted, browser security rules prevent reading or serializing the canvas: toBlob() or toDataURL() can throw a SecurityError.

  • Prefer same-origin SVG files. If the SVG is hosted on another domain, that server must return suitable CORS permission.
  • Set CORS mode before assigning the image URL when needed. For a cross-origin source that permits it, set image.crossOrigin = "anonymous" before image.src = svgUrl. This request setting does not grant permission by itself; the remote server must also allow the request.
  • Check resources inside the SVG. SVGs used as images have restrictions on external resource loading. MDN documents that those resources cannot be loaded in this context unless inlined as data URLs. External images, fonts, or other dependencies may be absent even if the SVG file itself loads.
  • Use inline or embedded assets where possible. This reduces dependence on separate resource requests and makes the rendered result more predictable.

Choose between browser canvas and Inkscape

Approach Best fit Key consideration
Browser canvas A web page or client-side feature that needs to render an SVG and offer a PNG download. You control the canvas pixel dimensions; image loading and CORS rules affect whether export succeeds.
Inkscape CLI Converting local files in a desktop workflow or build pipeline, including repeated or batch exports. Install Inkscape and check the installed version’s manual for current command-line flags.

Inkscape documents a command-line export such as inkscape --export-type="png" my_file.svg. Its CLI also supports exporting selected SVG object IDs and batch processing. Because command details can vary by version, confirm the supported options in the manual for the version installed on your machine.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshoot common conversion failures

The exported PNG is blank or incomplete

  • Confirm the image decoded before calling drawImage(); inspect rejected promises from image.decode().
  • Check that the SVG has usable root dimensions and a viewBox that includes the artwork.
  • Wait for any required fonts or resources to be available. SVG image contexts may not load external dependencies unless they are inlined as data URLs.
  • Verify the canvas dimensions are nonzero and that the drawing coordinates fit inside them.

Export throws SecurityError

This usually indicates a tainted canvas. Check whether the SVG or an image it uses came from another origin. Serve the asset from the same origin, inline the needed content, or configure the remote server to return appropriate CORS headers. Adding crossOrigin to the image without server permission is not a fix.

The PNG is stretched or cropped

Compare the source aspect ratio with the canvas ratio. The four-argument drawImage(image, 0, 0, width, height) scales the full image into the requested rectangle, so mismatched ratios distort it. Use proportional dimensions. If you intentionally want a crop, calculate source and destination rectangles explicitly with the nine-argument form of drawImage().

The output is blurry

The PNG cannot preserve vector scalability. Export at the pixel dimensions required for the final display, and increase both dimensions proportionally if it must be viewed larger or on a high-density display. Avoid enlarging a small PNG afterward.

toBlob() returns null

Handle the callback’s null case rather than assuming encoding succeeded. Confirm the canvas has valid dimensions and the requested MIME type is supported. PNG is the browser-required canvas format, so explicitly passing "image/png" is appropriate.

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

Performance and reliability considerations

For ordinary browser-side conversion, the main cost is the amount of raster data: a canvas with width w and height h contains w × h pixels before browser overhead and encoding. Very large dimensions can consume substantial memory. Select only as many pixels as the destination needs, and release temporary object URLs after their use. For many files or repeatable build output, a local CLI workflow such as Inkscape can be easier to automate than opening a page for each conversion.

The browser route depends on the SVG rendering correctly and on security rules allowing canvas export. Treat failed image loads, missing external resources, CORS errors, and encoding failures as separate cases so the user receives a useful error rather than a silent empty download.

Or skip the browser setup

If the SVG is already displayed on a publicly reachable webpage and you want a screenshot of that page rather than a conversion of an arbitrary SVG file, ScreenshotNeo can return a PNG in one GET request. It captures webpages; it is not a substitute for the canvas method when you need to rasterize a standalone SVG asset with exact dimensions.

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

Replace the target URL with the webpage containing the SVG. For this PNG workflow, request PNG output using the API’s documented format option; consult the ScreenshotNeo documentation for current parameters. Cookie banners, newsletter popups, and chat widgets can be removed before capture, with each step configurable. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed, and response headers identify the page verdict and billing status. Its MCP server offers take_screenshot, get_page_info, and capture_pdf for AI-agent clients. The Free plan includes 1,000 shots a month with no card; paid plans start at $5 for 3,000 shots. Sign up free for 1,000 screenshots a month with no card.

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

Frequently Asked Questions

Can I convert an SVG element directly with JavaScript without saving it first?

Yes. Serialize the inline SVG element, load the serialized content as an SVG Blob URL, and draw it to canvas as shown above.

Does a PNG keep the SVG’s vector quality?

No. PNG is a raster image with fixed pixel dimensions; the SVG remains the better format when later resizing without loss of sharpness matters.

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.