I want to convert SVG into bitmap images (like JPEG, PNG, etc.) through JavaScript.
Svg to png can be converted depending on conditions:
svg is in format SVG (string) paths:new Path2D() and set svg as parametercanvas.toDataURL() as src.example:
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
let svgText = 'M10 10 h 80 v 80 h -80 Z';
let p = new Path2D('M10 10 h 80 v 80 h -80 Z');
ctx.stroke(p);
let url = canvas.toDataURL();
const img = new Image();
img.src = url;
Note that Path2D not supported in ie and partially supported in edge. Polyfill solves that:
https://github.com/nilzona/path2d-polyfill
svg blob and draw on canvas using .drawImage():Nice description: https://web.archive.org/web/20200125162931/http://ramblings.mcpher.com:80/Home/excelquirks/gassnips/svgtopng
Note that in ie you will get exception on stage of canvas.toDataURL(); It is because IE has too high security restriction and treats canvas as readonly after drawing image there. All other browsers restrict only if image is cross origin.
canvg JavaScript library. It is separate library but has useful functions.Like:
ctx.drawSvg(rawSvg);
var dataURL = canvas.toDataURL();