我正在尝试使用javascript将通过d3.js获得的SVG图形导出为JPG图像。但是最终的图像没有正确显示,而是绘制了一个黑色区域,包围着图形的线条。这里有两张图片,顶部是SVG,底部是最终的JPG图像。我编写的代码如下:
root_node = d3.select("svg")
.attr("version", 1.1)
.attr("xmlns", "http://www.w3.org/2000/svg")
.node();
s_xml = (new XMLSerializer).serializeToString(root_node);
var imgsrc = 'data:image/svg+xml,'+ s_xml;
var img = '<img src="'+imgsrc+'">';
var canvas = document.createElement("canvas");
canvas.width = 1600;
canvas.height = 600;
context = canvas.getContext("2d");
var image = new Image;
image.src = imgsrc;
image.onload = function() {
context.drawImage(image, 0, 0);
context.fillStyle = 'white';
context.globalCompositeOperation = "destination-over";
context.fillRect(0, 0, canvas.width, canvas.height);
var canvasdata = canvas.toDataURL("image/jpeg");
var jpgimg = '<img src="'+canvasdata+'">';
d3.select("body").append("svgdataurl").html(jpgimg);
});
有谁知道颜色转换错误的原因吗?先感谢您!