Convert SVG to image (JPEG, PNG, etc.) in the browser

前端 未结 9 1054
春和景丽
春和景丽 2020-11-21 23:38

I want to convert SVG into bitmap images (like JPEG, PNG, etc.) through JavaScript.

9条回答
  •  逝去的感伤
    2020-11-22 00:06

    Svg to png can be converted depending on conditions:

    1. If svg is in format SVG (string) paths:
    • create canvas
    • create new Path2D() and set svg as parameter
    • draw path on canvas
    • create image and use canvas.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

    1. Create svg blob and draw on canvas using .drawImage():
    • make canvas element
    • make a svgBlob object from the svg xml
    • make a url object from domUrl.createObjectURL(svgBlob);
    • create an Image object and assign url to image src
    • draw image into canvas
    • get png data string from canvas: canvas.toDataURL();

    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.

    1. Use canvg JavaScript library. It is separate library but has useful functions.

    Like:

    ctx.drawSvg(rawSvg);
    var dataURL = canvas.toDataURL();
    

提交回复
热议问题