save/export an SVG file after creating an SVG with D3.js

Posted in :

把程式產生的SVG 另存新檔的方法:

const svgData = $("#you_chart_div")[0].outerHTML;
const svgBlob = new Blob([svgData], {type:"image/svg+xml;charset=utf-8"});
const objectUrl = URL.createObjectURL(svgBlob);
const downloadLink = document.createElement("a");
downloadLink.href = objectUrl; = "your_filename.svg";
  • 該不該用 outerHTML 還是 innerHTML, 取決於有沒有 append SVG 到 div 之中, 如果是用 append, 則使用 innerHTML 即可.
  • innerHTML / outerHTML 是 javascript 寫法, 如果全用 jQuery object, 請使用 .html() 即可取得 innerHTML.

svg 轉 png, 請參考:
How to Convert an SVG to an Image in the Browser?

網路上的範例: SVG D3 to PNG

var doctype = '<?xml version="1.0" standalone="no"?>'
  + '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "">';

// serialize our SVG XML to a string.
var source = (new XMLSerializer()).serializeToString('svg').node());

// create a file blob of our SVG.
var blob = new Blob([ doctype + source], { type: 'image/svg+xml;charset=utf-8' });

var url = window.URL.createObjectURL(blob);

// Put the svg into an image tag so that the Canvas element can read it in.
var img ='body').append('img')
 .attr('width', 100)
 .attr('height', 100)

img.onload = function(){
  // Now that the image has loaded, put the image into a canvas element.
  var canvas ='body').append('canvas').node();
  canvas.width = 100;
  canvas.height = 100;
  var ctx = canvas.getContext('2d');
  ctx.drawImage(img, 0, 0);
  var canvasUrl = canvas.toDataURL("image/png");
  var img2 ='body').append('img')
    .attr('width', 100)
    .attr('height', 100)
  // this is now the base64 encoded version of our PNG! you could optionally 
  // redirect the user to download the PNG by sending them to the url with 
  // `window.location.href= canvasUrl`.
  img2.src = canvasUrl; 
// start loading the image.
img.src = url;


發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *