JavaScript - 使用SVG图表+ HTML和图像导出Div

时间:2016-11-15 05:35:11

标签: javascript jquery angularjs svg highcharts

我们有角度js应用程序,它使用highchart js库,它将图表呈现为SVG。我们已经制作了几个显示数据组合的小部件,比如在一些小部件中我们只有SVG图表,有些我们只有使用angular指令呈现的表格数据,而在某些小部件中我们有两者的组合,即一些图表+一些HTML(它可以是简单的子弹列表,也可以说是用角度渲染的表格数据。现在我们想要提供功能,以便每个小部件都可以导出为图像。

我们遇到了这个使用html2canvas库的示例 jsfiddle.net/8ypxW/3 / ,并且只使用HTML数据,但SVG图表不会随此导出。

我们考虑通过C#从服务器端生成图像,但是每个小部件都是使用js库(highchart& angular)生成的,所以在这种情况下我们在服务器端没有任何直接支持。

上述方案有哪些解决方案?或者可以通过其他方法实现类似的目标。

3 个答案:

答案 0 :(得分:3)

我认为dom-to-image.js比html更准确到画布,这里有一些技巧:

dom-to-image让你从html svg数据生成url格式,是的我知道你为什么要这样做,它更准确,用svg将图像画在画布里面(你需要什么)在你的情况下,或者如果你需要在我的例子中打印图像中的整个页面,那么更复杂的东西)。从该画布中,您可以拉动图像,调整大小,下载它。

版权: http://jsfiddle.net/gregfedorov/Qh9X5/9/http://jsfiddle.net/christopheviau/v6VMf/



Base* base = buildDerived(1);  

///dom to svg module
document.getElementById('downloadbody').onclick= function(){
  var wrapper = document.getElementsByTagName("BODY")[0];
  //dom to image
  domtoimage.toSvg(wrapper).then(function (svgDataUrl) {
  //download function    
  downloadPNGFromAnyImageSrc(svgDataUrl);
  });
}

document.getElementById('downloadcircle').onclick= function(){
  var wrapper = document.getElementById('circle');
  //dom to image
  domtoimage.toSvg(wrapper).then(function (svgDataUrl) {
  //download function    
  downloadPNGFromAnyImageSrc(svgDataUrl);
  });
}

document.getElementById('downloadtable').onclick= function(){
  var wrapper = document.getElementById('table');
  //dom to image
  domtoimage.toSvg(wrapper).then(function (svgDataUrl) {
  //download function    
  downloadPNGFromAnyImageSrc(svgDataUrl);
  });
}

function downloadPNGFromAnyImageSrc(src)
{
  //recreate the image with src recieved
  var img = new Image;
  //when image loaded (to know width and height)
  img.onload = function(){
    //drow image inside a canvas
    var canvas = convertImageToCanvas(img);
    //get image/png from convas
    var pngImage =  convertCanvasToImage(canvas);
    //download
    var anchor = document.createElement('a');
    anchor.setAttribute('href', pngImage.src);
    anchor.setAttribute('download', 'image.png');
    anchor.click();
  };
  
  img.src = src;


	// Converts image to canvas; returns new canvas element
  function convertImageToCanvas(image) {
        var canvas = document.createElement("canvas");
        canvas.width = image.width;
        canvas.height = image.height;
        canvas.getContext("2d").drawImage(image, 0, 0);
        return canvas;
    }
    
    
    // Converts canvas to an image
    function convertCanvasToImage(canvas) {
        var image = new Image();
        image.src = canvas.toDataURL("image/png");
        return image;
    }
}



////// svg's generations

////CIrcle Modeule///////
var dataset = {
  apples: [53245, 28479, 19697, 24037, 40245],
};

var width = 460,
    height = 300,
    radius = Math.min(width, height) / 2;

var color = d3.scale.category20();

var pie = d3.layout.pie()
    .sort(null);

var arc = d3.svg.arc()
    .innerRadius(radius - 100)
    .outerRadius(radius - 50);

var svg = d3.select("#circle").append("svg")
    .attr("width", width)
    .attr("height", height)
    .append("g")
    .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

var path = svg.selectAll("path")
    .data(pie(dataset.apples))
  .enter().append("path")
    .attr("fill", function(d, i) { return color(i); })
    .attr("d", arc);


// Table module ////////////////////////////////////
var Table = function module() {
    var opts = {
        width: 200,
        height: 200,
        margins: {top: 20, right: 20, bottom: 20, left: 20}
    };

    function exports(selection) {
        selection.each(function (dataset) {

            //________________________________________________
            // Data
            //________________________________________________
            var columnLabel = dataset.columnLabel;
            var rowLabel = dataset.rowLabel;
            var value = dataset.value;

            //________________________________________________
            // DOM preparation
            //________________________________________________
            // Size
            var chartW = Math.max(opts.width - opts.margins.left - opts.margins.right, 0.1);
            var chartH = Math.max(opts.height - opts.margins.top - opts.margins.bottom, 0.1);

            // SVG
            var parentDiv = d3.select(this).html('');
            var svg = parentDiv.append('svg').attr('width', opts.width).attr('height', opts.height);
            var visSvg = svg.append('g').attr('class', 'vis-group').attr('transform', 'translate(' + opts.margins.left + ',' + opts.margins.top + ')');
            var tableBodySvg = visSvg.append('g').attr('class', 'chart-group');
            var tableHeaderSvg = visSvg.append('g').attr('class', 'chart-group');
            var rowHeaderSvg = tableHeaderSvg.append('g').attr('class', 'row-header');
            var colHeaderSvg = tableHeaderSvg.append('g').attr('class', 'col-header');

            //________________________________________________
            // Table
            //________________________________________________
            var rowHeaderLevelNum = 1;
            var colHeaderLevelNum = 1;
            var cellH = chartH / (value.length + rowHeaderLevelNum);
            var cellW = chartW / (value[0].length + colHeaderLevelNum);

            // Row header
            var rowHeaderCell = rowHeaderSvg.selectAll('rect.row-header-cell')
                .data(rowLabel);
            rowHeaderCell.enter().append('rect')
                .attr({
                    class:'row-header-cell',
                    width:cellW, height:cellH,
                    x: 0,
                    y: function(d, i){return i * cellH + (cellH * colHeaderLevelNum)}
                })
                .style({fill:'#eee', stroke:'silver'});

            // Row header text
            rowHeaderCell.enter().append('text')
                .attr({
                    class:'row-header-content',
                    x: 0,
                    y: function(d, i){return i * cellH + (cellH * colHeaderLevelNum)},
                    dx: cellW/2,
                    dy: cellH/2
                })
                .style({fill:'black', 'text-anchor':'middle'})
                .text(function(d, i){return d;});

            // Col header
            var colHeaderCell = colHeaderSvg.selectAll('rect.col-header-cell')
                .data(columnLabel);
            colHeaderCell.enter().append('rect')
                .attr({
                    class:'col-header-cell',
                    width:cellW, height:cellH,
                    x: function(d, i){return i * cellW + (cellW * rowHeaderLevelNum)},
                    y: 0
                })
                .style({fill:'#eee', stroke:'silver'});

            // Col header text
            colHeaderCell.enter().append('text')
                .attr({
                    class:'col-header-content',
                    x: function(d, i){return i * cellW + (cellW * rowHeaderLevelNum)},
                    y: 0,
                    dx: cellW/2,
                    dy: cellH/2
                })
                .style({fill:'black', 'text-anchor':'middle'})
                .text(function(d, i){return d;});

            // Body
            var row = tableBodySvg.selectAll('g.row')
                .data(value);
            row.enter().append('g')
                .attr('class', 'cell row')
                .each(function(pD, pI){
                    // Cells
                    var cell = d3.select(this)
                        .selectAll('rect.cell')
                        .data(pD);
                    cell.enter().append('rect')
                        .attr({
                            class:'cell', width:cellW, height:cellH,
                            x: function(d, i){return i * cellW + (cellW * rowHeaderLevelNum)},
                            y: function(d, i){return pI * cellH + cellH}
                        })
                        .style({fill:'white', stroke:'silver'});
                    // Text
                    cell.enter().append('text')
                        .attr({
                            class:'cell-content', width:cellW, height:cellH,
                            x: function(d, i){return i * cellW + (cellW * rowHeaderLevelNum)},
                            y: function(d, i){return pI * cellH + cellH},
                            dx: cellW/2,
                            dy: cellH/2
                        })
                        .style({fill:'black', 'text-anchor':'middle'})
                        .text(function(d, i){return d;});
                });
        });
    }

    exports.opts = opts;
    createAccessors(exports, opts);
    return exports;
};
  
// Helper function ////////////////////////////////////                       
var createAccessors = function(visExport) {
    for (var n in visExport.opts) {
        if (!visExport.opts.hasOwnProperty(n)) continue;
        visExport[n] = (function(n) {
            return function(v) {
                return arguments.length ? (visExport.opts[n] = v, this) : visExport.opts[n];
            }
        })(n);
    }
};                        
 
// Usage ////////////////////////////////////                        
var dataset = {
    rowLabel: ['A', 'B', 'C', 'D', 'E'],
    columnLabel: ['P', 'Q', 'R', 'S'],
    value: [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], [17, 18, 19, 20]]
};
                        
var width = 400;
var height = 300;

var table = Table().width(width).height(height);

d3.select('#table')
    .datum(dataset)
    .call(table);

body {
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
  margin: auto;
  position: relative;
  width: 960px;
  background-color:blue;
}

text {
  font: 10px sans-serif;
}

form {
  position: absolute;
  right: 10px;
  top: 10px;
}




答案 1 :(得分:0)

phantomjs会将html + svg转换为图片。它需要将服务器端作为单独的进程运行,但可以从C#调用。

答案 2 :(得分:0)

也许您可以尝试SVG2Bitmap首先将SVG转换为图像,然后使用html2canvas。这是此类question中使用的方法。