我目前正在开展一个项目,我需要导出从d3.js创建的SVG图像。
我在互联网上搜索,尝试了几种方法,但没有任何作用。当他看到米色框架时,我的“力布局”无法识别。我不明白。
var svg2 = document.querySelector('svg');
var img = document.querySelector('img');
var canvas = document.querySelector('canvas');
// get svg data
var xml = new XMLSerializer().serializeToString(svg2);
// make it base64
var svg64 = btoa(xml);
var b64Start = 'data:image/svg+xml;base64,';
// prepend a "header"
var image64 = b64Start + svg64;
// set it as the source of the img element
img.src = image64;
// draw the image onto the canvas
canvas.getContext('2d').drawImage(img, 0, 0);
function dlCanvas() {
var dt = canvas.toDataURL('image/png'); // << this fails in IE/Edge...
dt = dt.replace(/^data:image\/[^;]*/, 'data:application/octet-stream');
dt = dt.replace(/^data:application\/octet-stream/, 'data:application/octet-stream;headers=Content-Disposition%3A%20attachment%3B%20filename=Canvas.png');
this.href = dt;
};
document.getElementById('dl').addEventListener('click', dlCanvas, false);
HTML
<!-- <div id="graph"></div>--><!-- La visualisation, c'est le "div" a gauche, cf. script "main.js" -->
<div id ="graph">
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" height="500" width="1050">
<rect class="canvas" width="100%" height="100%" fill='#f5f5f5'></rect>
</svg>
</div>
Image <img></img>
<canvas width="1000" height="500"> </canvas>