Conversion of SVG to PNG (Base64) with JavaScript

Conversion of SVG to PNG (Base64) with JavaScript

Takahiro Iwasa
(岩佐 孝浩)
Takahiro Iwasa (岩佐 孝浩)
2 min read
JavaScript RxJS

I wrote a code to convert SVG to PNG (Base64) using RxJS.

You can pull an example code used in this post from my GitHub repository.

Images will be processed by the following order.

  1. Creating a canvas element. Please specify a scaling coefficient for better quality if the canvas generates low quality images.
  2. Creating an Image object
  3. Converting SVG to Base64
  4. Setting the Base64 to the Image#src
  5. Rendering the image on the canvas after loading the image
  6. Obtaining the data URI using toDataURL
import { filter, fromEvent, map, Observable, take, throwIfEmpty } from 'rxjs';

/**
 * Convert SVG to PNG (Base64).
 *
 * @param svgElement
 * @param scale A scaling coefficient
 * @return Observable<string>
 */
export const svgToPng = (svgElement: SVGSVGElement, scale = 4): Observable<string> => {
  const canvas = createCanvas(svgElement, scale);
  const image = new Image();

  const source = fromEvent(image, 'load').pipe(
    take(1),
    map(() => canvas.getContext('2d', {})),
    throwIfEmpty(),
    filter(Boolean),
    map((context) => {
      context.drawImage(image, 0, 0, canvas.width, canvas.height);
      return canvas.toDataURL('image/png', 1);
    }),
  );

  image.src = svgToBase64(svgElement);
  return source;
}

const createCanvas = (svgElement: SVGSVGElement, scale = 4): HTMLCanvasElement => {
  const canvas = document.createElement('canvas');
  canvas.width = svgElement.width.baseVal.value * scale;
  canvas.height = svgElement.height.baseVal.value * scale;
  return canvas;
};

const svgToBase64 = (svgElement: SVGSVGElement): string => {
  const svg = new XMLSerializer().serializeToString(svgElement);
  const base64 = window.btoa(unescape(encodeURIComponent(svg)));
  return `data:image/svg+xml;charset=utf-8;base64,${base64}`;
};
Takahiro Iwasa
(岩佐 孝浩)

Takahiro Iwasa (岩佐 孝浩)

Software Developer at iret, Inc.
Architecting and developing cloud native applications mainly with AWS. Japan AWS Top Engineers 2020-2023