我有一个将svg保存到png的脚本。我从这里得到了这个脚本:svg to png 谢谢你。
我尝试粘贴此代码以用于将生成的网格保存到png。但它不起作用。
这是html的一部分:
<div class="span6" style="text-align:center">
<div id="container"></div>
<!--These are for save SVG-->
<button id="save">Save as Image</button>
<div id="svgdataurl"></div>
<div id="pngdataurl"></div>
<canvas width="960" height="500"></canvas>
</div>
这是javascript的一部分:
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
d3.select("#save").on("click", function(){
var html = d3.select("svg")
.attr("version", 1.1)
.attr("xmlns", "http://www.w3.org/2000/svg")
.node().parentNode.innerHTML;
console.log(html);
var imgsrc = 'data:image/svg+xml;base64,'+ btoa(html);
var img = '<img src="'+imgsrc+'">';
d3.select("#svgdataurl").html(img);
var canvas = document.querySelector("canvas"),
context = canvas.getContext("2d");
var image = new Image;
image.src = imgsrc;
image.onload = function() {
context.drawImage(image, 0, 0);
//save and serve it as an actual filename
binaryblob();
var a = document.createElement("a");
a.download = "sample.png";
a.href = canvas.toDataURL("image/png");
var pngimg = '<img src="'+a.href+'">';
d3.select("#pngdataurl").html(pngimg);
a.click();
};
});
function binaryblob(){
var byteString = atob(document.querySelector("canvas").toDataURL().replace(/^data:image\/(png|jpg);base64,/, ""));
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
var dataView = new DataView(ab);
var blob = new Blob([dataView], {type: "image/png"});
var DOMURL = self.URL || self.webkitURL || self;
var newurl = DOMURL.createObjectURL(blob);
var img = '<img src="'+newurl+'">';
d3.select("#img").html(img);
}
</script>
但我也将整个代码粘贴到jasfiddle中: