We know that canvas canvas can be handy for JS native support to image format and download, but SVG vector graphics does not have this native support.
The image download mechanism of SVG graphics has been studied, and its implementation principle is basically to collect SVG code information on the browser side and send it to the server side, which is converted into picture format by the back-end program and reflected to the browser-side download in the form of Highchart.
Recently in the project there is a need to dump a non-highchart svg map into a picture and download the feature.
The idea of simulating Highchart was realized, but the study found that the SVG code information of the map was as much as 20,000 bytes, whereas the Highchart back-end mapping program had a byte limit, so it could not be processed.
Then the foreign community to discuss the method is also a front-end collaborative processing to complete this function, so that the implementation will be more heavy, and deployment inconvenience.
After a search, we finally found a method that does not rely on any external libraries, frames, and only through the browser-side JS can be implemented. The specific source address of the code implementation has been forgotten, and this preserves the copyright of the original author of the Code.
First, we agree that the context structure of SVG is as follows:
<Div Class="Svg-wrap"><Svg> </ < Span class= "Hljs-name" >svg></< Span class= "Hljs-tag" > div
We can then convert the SVG graphic to an image and download it using the following code:
var svgxml = $ ('. Svg-wrap '). html ();var image =New Image (); image.src =' Data:image/svg+xml;base64, ' +Window.btoa (Unescape (encodeURIComponent (Svgxml));Writes a base64 encoded SVG stream to a picture objectvar canvas =document.createelement (' canvas '); //Prepare empty canvas Canvas.width = $ ('. Svg-wrap svg '). width (); canvas.height = $ ('. Svg-wrap svg '). Height (); var context = Canvas.getcontext (' 2d '); //Get the 2d drawing context of the canvas context.drawimage (image, 0, 0); var a = document.createelement (' a '); a.href = Canvas.todataurl (' image/png '); //Export the information in the canvas as PNG image data A.download = "Mapbymathartsys"; //Set download name A.click (); //Click Trigger to download
Original address: HTTP//Source address has been forgotten, the foreign community found
JS implementation of SVG graphics dump image download [go]