3

I am trying to export a graph from SVG (obtained through d3.js) to a JPG image using javascript.

The fact is that the final image do not show the picture properly but it draws a black area enclosing the lines of the graph. Here they are the two images. At the top of the page the SVG is represented whereas the final JPG image is depicted.

The code I have written is the following:

    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);

    });

Anyone knows the reason of the wrong colours transformation? Thanks in advance!

4

1 回答 1

6

您必须在 D3 代码中直接给出折线图的 CSS。

lineChart.append("path")
.attr("class", "lineChart")
.attr("stroke-width", 1)
.attr("fill","none")
.attr("d", valueline(lineChartData));
于 2017-06-02T06:32:46.813 回答