On this page
SVG text and three arrows that point to PNG, JPEG, and JPG, representing three different formats that SVG can be converted to.

Convert SVG to PNG, JPEG, or WebP image using JavaScript in the browser

Learn how to convert SVG to various image formats like PNG, JPEG, and WebP in the browser using JavaScript.

To convert SVG to PNG, JPG, or WebP WebP is a modern raster graphics file format created by Google to provide more powerful lossless and lossy compression for images on the web. It is designed to replace the JPEG, PNG, and GIF file formats, and it supports animation and alpha transparency. WebP images are less in size than popular formats such as PNG and JPEG, which might result in faster website load times., you can use the DOM API to create an object URL from the SVG code, load it into an image element, and then write that image to a Canvas. Finally, you can use the toDataURL() method to convert the Canvas to a base64 encoded PNG image.

Example code for converting SVG to PNG image

Here’s an example of how you can do this:

Convert SVG to PNG code
const svgAsString = 'SVG code';

const svgBlob = new Blob([svgAsString], {
  type: 'image/svg+xml'
});
const svgObjectUrl = globalThis.URL.createObjectURL(svgBlob);
const img = document.createElement('img');

const onImageLoaded = () => {
  const canvas = document.createElement('canvas');
  const context = canvas.getContext('2d');
  const createdImage = document.createElement('img');

  context.drawImage(img, 0, 0);
  createdImage.src = canvas.toDataURL('image/png');

  // Here the image is ready to use, e.g., document.body.appendChild(createdImage);
  globalThis.URL.revokeObjectURL(svgObjectUrl);
};

img.addEventListener('load', onImageLoaded);
img.src = svgObjectUrl;

Brief explanation of SVG to image conversion

You may notice the globalThis usage in the code. The globalThis property in JavaScript provides a standard way of accessing the global this value (and hence the global object itself) across environments. It aims to consolidate the increasingly fragmented ways of accessing the global object by providing a consistent way to access it across all JavaScript environments. This is particularly useful because the global object has different names in different environments, such as window in a web browser, self in a web worker, or global in Node.js.

By using globalThis, your code will work in window and non-window contexts without having to write additional checks or use different syntaxes.

toDataURL() is a method in JavaScript that is used to return a data URL containing a representation of an image in the format specified by the type parameter. The desired file format and image quality may be specified. If the file format is not specified, or if the given format is not supported, then the data will be exported as image/png. The method is used on a canvas element and returns a string that represents the image. The syntax for using toDataURL() is canvas.toDataURL(type, encoderOptions). The type parameter is optional and indicates the image format, while the encoderOptions parameter is also optional and indicates the image quality for JPEG images to be used when creating the image. It is a number between 0 and 1, with 1 being the highest quality.

Considerations and limitations

  • The toDataURL() method in HTMLCanvasElement is used to convert a canvas element into a data URL. It returns a data URL containing a representation of the image in the format specified by the type parameter. If the type parameter is not specified or if the given format is not supported, the data will be exported as image/png. However, many browsers also support additional formats including image/jpeg and image/webp.
  • The toDataURL() method may throw a security exception if the canvas contains images that are not hosted on the same domain as the code executing it. This is a security measure to prevent unauthorized access to images from different domains.
  • The mime-type for JPG and JPEG aren’t the same. Some browsers may support only image/jpg, but not image/jpeg, when using canvas.toDataURL(mime-type). The MIME types image/jpg and image/jpeg are essentially the same. Both refer to the same file format, which is the Joint Photographic Experts Group (JPEG) standard. The only difference is that image/jpeg is the official MIME type according to the Internet Assigned Numbers Authority (IANA), whereas image/jpg is less formal and could potentially be seen as incorrect, but is commonly used nonetheless.
  • To get SVG width and height you may consider using baseVal property. The baseVal property is used in SVG to get or set the base value of a given attribute before any animations are applied. It is part of the SVGAnimatedString and SVGAnimatedLength interfaces and allows getting or setting the initial value of an attribute, without considering any animations that might be affecting it.

    Get width and height of SVG
    const svgElement = document.querySelector('#mySvg');
    
    const svgHeight = svgElement.viewBox.baseVal.height;
    const svgWidth = svgElement.viewBox.baseVal.width;

Managing memory during the conversion process

Each time you call createObjectURL(), a new object URL is created, even if you’ve already created one for the same object. Each of these must be released by calling URL.revokeObjectURL() when you no longer need them.

Browsers will automatically release object URLs when the document is unloaded. However, for optimal performance and memory use, if there are safe times to explicitly unload them, do so.

Converting SVG to JPG, JPEG, or WebP format

To convert the SVG to JPG, JPEG or WebP you need to provide correct mime-type for canvas.toDataURL(mime-type).

  • JPG: image/jpg.
  • JPEG: image/jpeg.
  • WebP: image/webp.

Alternative methods for SVG conversion

You may also want to convert SVG in the following scenarios:

  • Convert the SVG file to PNG, JPG, JPEG, or WebP and save it.
  • Create an image from the provided SVG code string.
  • Create an image from the HTML SVG element.

Converting SVG to image online

Explore the source of the HTML and JavaScript code to find out the implementation details.

Related posts

Comments

Leave a Reply

Search in sitelint.com

Struggling with writing tests for accessibility?

You can cut 80% of the time you spend writing tests using SiteLint.

Real-user monitoring for Accessibility, Performance, Security, SEO & Errors (SiteLint)