Skip to content

Instantly share code, notes, and snippets.

@arlm
Created December 12, 2023 12:15
Show Gist options
  • Save arlm/c32a8f94f28620c6745271974294a5e5 to your computer and use it in GitHub Desktop.
Save arlm/c32a8f94f28620c6745271974294a5e5 to your computer and use it in GitHub Desktop.
/*
Steps to draw an SVG to canvas:
* Find the width and height of an SVG
* Clone the SVG node
* Create a blob object from the SVG
* Create a URL for the blob
* Load the URL into an image element
* Create a canvas with width and height of the SVG
* Draw the image to the canvas
*/
// Find the width and height of an SVG
var svgElement = document.getElementById('svg-item-id');
let {width, height} = svgElement.getBBox();
// Clone the SVG node
let clonedSvgElement = svgElement.cloneNode(true /* deep clone */);
// Create a blob object from the SVG
let outerHTML = clonedSvgElement.outerHTML, blob = new Blob([outerHTML],{type:'image/svg+xml;charset=utf-8'});
// Create a URL for the blob
let URL = window.URL || window.webkitURL || window;
let blobURL = URL.createObjectURL(blob);
// Load the URL into an image element
let image = new Image();
var download = function(href, name) {
var link = document.createElement('a');
link.download = name;
link.style.opacity = "0";
document.append(link);
link.href = href;
link.click();
link.remove();
}
var downloadImage = function(canvas) {
let png = canvas.toDataURL(); // default png
download(png, "image.png");
let jpeg = canvas.toDataURL('image/jpg'); // 0.92 quality
download(jpeg, "image.jpg");
let webp = canvas.toDataURL('image/webp', 0.5 /* quality */);
download(webp, "image.webp");
}
// Create a canvas with width and height of the SVG
image.onload = () => {
let canvas = document.createElement('canvas');
canvas.widht = width;
canvas.height = height;
let context = canvas.getContext('2d');
// draw image in canvas starting left-0 , top - 0
context.drawImage(image, 0, 0, width, height );
downloadImage(canvas);
};
image.src = blobURL;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment