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

Posted in :

把程式產生的SVG 另存新檔的方法:
https://stackoverflow.com/questions/23218174/how-do-i-save-export-an-svg-file-after-creating-an-svg-with-d3-js-ie-safari-an

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;
downloadLink.download = "your_filename.svg";
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
  • 該不該用 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?
https://stackoverflow.max-everyday.com/2023/03/how-to-convert-an-svg-to-an-image-in-the-browser/

網路上的範例: SVG D3 to PNG
https://gist.github.com/vicapow/758fce6aa4c5195d24be

var doctype = '<?xml version="1.0" standalone="no"?>'
  + '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">';

// serialize our SVG XML to a string.
var source = (new XMLSerializer()).serializeToString(d3.select('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 = d3.select('body').append('img')
 .attr('width', 100)
 .attr('height', 100)
 .node();


img.onload = function(){
  // Now that the image has loaded, put the image into a canvas element.
  var canvas = d3.select('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 = d3.select('body').append('img')
    .attr('width', 100)
    .attr('height', 100)
    .node();
  // 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;

發佈留言

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