Analysis of image download in browser

Posted by adamski on Sat, 04 Jan 2020 12:29:43 +0100

As a result of the project demand reason, looked up in the browser picture download related material earnestly, summarized several parts.

1. Save SVG as PNG

 In IE, it seems that SVG can only be saved locally as PNG by right clicking SVG.
 In non IE browser, it can be realized by the following code:
    let serializer = new XMLSerializer(),
    //Converts or "serializes" an XML document or Node object into a string of unresolved XML tags
        source = serializer.serializeToString(svg.node());
        //Convert svg to a string
    source = '<?xml version="1.0" standalone="no"?>\r\n' + source;
    var url = "data:image/svg+xml;charset=utf-8," + encodeURIComponent(source);
    //Turn SVG into data stream
    let canvas = document.createElement("canvas");//Create a canvas label
    canvas.width = width;
    canvas.height = height;
    let context = canvas.getContext("2d");//2D drawing on canvas
    let image = new Image();//Create a new image label
    image.src = url;
    image.onload = function () {
      context.drawImage(image, 0, 0);//Draw image in canvas
      var a = document.createElement("a");
      a.download = "svg.png";//This is the name of the image. The a.download property is not supported by IE
      a.href = canvas.toDataURL();//Convert canvas data to base64
      a.click();
    };

You can also use the plug-in canvg.js (convert SVG to canvas) to implement the code as follows:

//Remember to import the canvg.js file or download it from npm
let canvas = document.createElement("canvas");
canvas.width = 720;//This is based on your actual needs
canvas.height = 720;
canvg(canvas,svgHTML);//The function in canvg.js is used to change svg into canvas
//Canvas is the container where you want to store canvas. I use a canvas tag here. SVG html is the SVG tag you want to convert
var a = document.createElement("a");
a.download = "svg.png";
 a.href = canvas.toDataURL();//canvas.toDataURL() will report security errors in IE, which should be due to cross domain problems
 a.click();

2. Save canvas as PNG picture

if(!!window.ActiveXObject || "ActiveXObject" in window){
// IE browser;
γ€€γ€€let blob = canvas.msToBlob();
γ€€γ€€//Canvas is the canvas label in your page to be saved as PNG picture,. msToBlob() is the behavior of IE browser, originally canvas.toBlob().
    window.navigator.msSaveBlob(blob, 'svg.png');
    //This is IE's Blob data storage method
  }else{
// Non IE browser;
      var a = document.createElement("a");
      a.download = "svg.png";
      a.href = canvas.toDataURL();
      a.click();
  }

Topics: IE xml npm