windows.resize()无效

时间:2017-02-28 09:49:18

标签: javascript d3.js

大家好我在我的html body标签中使用d3图表。我想在调整浏览器窗口大小时自动调整d3图表的宽度和高度。

这里我附上了我的代码
d3.min.js <script src="https://d3js.org/d3.v3.min.js"></script>你可以从互联网上获取这个js代码 ,

d3-legend .js

(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
var helper = require('./legend');

module.exports = function(){

  var scale = d3.scale.linear(),
    shape = "rect",
    shapeWidth = 15,
    shapeHeight = 15,
    shapeRadius = 10,
    shapePadding = 2,
    cells = [5],
    labels = [],
    useClass = false,
    labelFormat = d3.format(".01f"),
    labelOffset = 10,
    labelAlign = "middle",
    labelDelimiter = "to",
    orient = "vertical",
    path,
    legendDispatcher = d3.dispatch("cellover", "cellout", "cellclick");

    function legend(svg){

      var type = helper.d3_calcType(scale, cells, labels, labelFormat, labelDelimiter);

      var cell = svg.selectAll(".cell").data(type.data),
        cellEnter = cell.enter().append("g", ".cell").attr("class", "cell").style("opacity", 1e-6);
        shapeEnter = cellEnter.append(shape).attr("class", "swatch"),
        shapes = cell.select("g.cell " + shape);

      //add event handlers
      helper.d3_addEvents(cellEnter, legendDispatcher);

      cell.exit().transition().style("opacity", 0).remove();

      helper.d3_drawShapes(shape, shapes, shapeHeight, shapeWidth, shapeRadius, path);

      helper.d3_addText(svg, cellEnter, type.labels)

      // sets placement
      var text = cell.select("text"),
        shapeSize = shapes[0].map( function(d){ return d.getBBox(); });

      //sets scale
      //everything is fill except for line which is stroke,
      if (!useClass){
        if (shape == "line"){
          shapes.style("stroke", type.feature);
        } else {
          shapes.style("fill", type.feature);
        }
      } else {
        shapes.attr("class", function(d){ return "swatch " + type.feature(d); });
      }

      var cellTrans,
      textTrans,
      textAlign = (labelAlign == "start") ? 0 : (labelAlign == "middle") ? 0.5 : 1;

      //positions cells and text
      if (orient === "vertical"){
        cellTrans = function(d,i) { return "translate(0, " + (i * (shapeSize[i].height + shapePadding)) + ")"; };
        textTrans = function(d,i) { return "translate(" + (shapeSize[i].width + shapeSize[i].x +
          labelOffset) + "," + (shapeSize[i].y + shapeSize[i].height/2 + 5) + ")"; };

      } else if (orient === "horizontal"){
        cellTrans = function(d,i) { return "translate(" + (i * (shapeSize[i].width + shapePadding)) + ",0)"; }
        textTrans = function(d,i) { return "translate(" + (shapeSize[i].width*textAlign  + shapeSize[i].x) +
          "," + (shapeSize[i].height + shapeSize[i].y + labelOffset + 8) + ")"; };
      }

      helper.d3_placement(orient, cell, cellTrans, text, textTrans, labelAlign);
      cell.transition().style("opacity", 1);

    }



  legend.scale = function(_) {
    if (!arguments.length) return legend;
    scale = _;
    return legend;
  };

  legend.cells = function(_) {
    if (!arguments.length) return legend;
    if (_.length > 1 || _ >= 2 ){
      cells = _;
    }
    return legend;
  };

  legend.shape = function(_, d) {
    if (!arguments.length) return legend;
    if (_ == "rect" || _ == "circle" || _ == "line" || (_ == "path" && (typeof d === 'string')) ){
      shape = _;
      path = d;
    }
    return legend;
  };

  legend.shapeWidth = function(_) {
    if (!arguments.length) return legend;
    shapeWidth = +_;
    return legend;
  };

  legend.shapeHeight = function(_) {
    if (!arguments.length) return legend;
    shapeHeight = +_;
    return legend;
  };

  legend.shapeRadius = function(_) {
    if (!arguments.length) return legend;
    shapeRadius = +_;
    return legend;
  };

  legend.shapePadding = function(_) {
    if (!arguments.length) return legend;
    shapePadding = +_;
    return legend;
  };

  legend.labels = function(_) {
    if (!arguments.length) return legend;
    labels = _;
    return legend;
  };

  legend.labelAlign = function(_) {
    if (!arguments.length) return legend;
    if (_ == "start" || _ == "end" || _ == "middle") {
      labelAlign = _;
    }
    return legend;
  };

  legend.labelFormat = function(_) {
    if (!arguments.length) return legend;
    labelFormat = _;
    return legend;
  };

  legend.labelOffset = function(_) {
    if (!arguments.length) return legend;
    labelOffset = +_;
    return legend;
  };

  legend.labelDelimiter = function(_) {
    if (!arguments.length) return legend;
    labelDelimiter = _;
    return legend;
  };

  legend.useClass = function(_) {
    if (!arguments.length) return legend;
    if (_ === true || _ === false){
      useClass = _;
    }
    return legend;
  };

  legend.orient = function(_){
    if (!arguments.length) return legend;
    _ = _.toLowerCase();
    if (_ == "horizontal" || _ == "vertical") {
      orient = _;
    }
    return legend;
  };

  d3.rebind(legend, legendDispatcher, "on");

  return legend;

};


},{"./legend":2}],2:[function(require,module,exports){
module.exports = {

d3_identity: function (d) {
  return d;
},

d3_mergeLabels: function (gen, labels) {

    if(labels.length === 0) return gen;

    gen = (gen) ? gen : [];

    var i = labels.length;
    for (; i < gen.length; i++) {
      labels.push(gen[i]);
    }
    return labels;
  },

d3_linearLegend: function (scale, cells, labelFormat) {
  var data = [];

  if (cells.length > 1){
    data = cells;

  } else {
    var domain = scale.domain(),
    increment = (domain[domain.length - 1] - domain[0])/(cells - 1),
    i = 0;

    for (; i < cells; i++){
      data.push(labelFormat(domain[0] + i*increment));
    }
  }

  return {data: data,
          labels: data,
          feature: function(d){ return scale(d); }};
},

d3_quantLegend: function (scale, labelFormat, labelDelimiter) {
  var labels = scale.range().map(function(d){
    var invert = scale.invertExtent(d),
    a = labelFormat(invert[0]),
    b = labelFormat(invert[1]);

    // if (( (a) && (a.isNan()) && b){
    //   console.log("in initial statement")
      return labelFormat(invert[0]) + " " + labelDelimiter + " " + labelFormat(invert[1]);
    // } else if (a || b) {
    //   console.log('in else statement')
    //   return (a) ? a : b;
    // }

  });

  return {data: scale.range(),
          labels: labels,
          feature: this.d3_identity
        };
},

d3_ordinalLegend: function (scale) {
  return {data: scale.domain(),
          labels: scale.domain(),
          feature: function(d){ return scale(d); }};
},

d3_drawShapes: function (shape, shapes, shapeHeight, shapeWidth, shapeRadius, path) {
  if (shape === "rect"){
      shapes.attr("height", shapeHeight).attr("width", shapeWidth);

  } else if (shape === "circle") {
      shapes.attr("r", shapeRadius)//.attr("cx", shapeRadius).attr("cy", shapeRadius);

  } else if (shape === "line") {
      shapes.attr("x1", 0).attr("x2", shapeWidth).attr("y1", 0).attr("y2", 0);

  } else if (shape === "path") {
    shapes.attr("d", path);
  }
},

d3_addText: function (svg, enter, labels){
  enter.append("text").attr("class", "label");
  svg.selectAll("g.cell text").data(labels).text(this.d3_identity);
},

d3_calcType: function (scale, cells, labels, labelFormat, labelDelimiter){
  var type = scale.ticks ?
          this.d3_linearLegend(scale, cells, labelFormat) : scale.invertExtent ?
          this.d3_quantLegend(scale, labelFormat, labelDelimiter) : this.d3_ordinalLegend(scale);

  type.labels = this.d3_mergeLabels(type.labels, labels);

  return type;
},

d3_placement: function (orient, cell, cellTrans, text, textTrans, labelAlign) {
  cell.attr("transform", cellTrans);
  text.attr("transform", textTrans);
  if (orient === "horizontal"){
    text.style("text-anchor", labelAlign);
  }
},

d3_addEvents: function(cells, dispatcher){
  var _ = this;

    cells.on("mouseover.legend", function (d) { _.d3_cellOver(dispatcher, d, this); })
        .on("mouseout.legend", function (d) { _.d3_cellOut(dispatcher, d, this); })
        .on("click.legend", function (d) { _.d3_cellClick(dispatcher, d, this); });
},

d3_cellOver: function(cellDispatcher, d, obj){
  cellDispatcher.cellover.call(obj, d);
},

d3_cellOut: function(cellDispatcher, d, obj){
  cellDispatcher.cellout.call(obj, d);
},

d3_cellClick: function(cellDispatcher, d, obj){
  cellDispatcher.cellclick.call(obj, d);
}

}

},{}],3:[function(require,module,exports){
var helper = require('./legend');

module.exports =  function(){

  var scale = d3.scale.linear(),
    shape = "rect",
    shapeWidth = 15,
    shapePadding = 2,
    cells = [5],
    labels = [],
    useStroke = false,
    labelFormat = d3.format(".01f"),
    labelOffset = 10,
    labelAlign = "middle",
    labelDelimiter = "to",
    orient = "vertical",
    path,
    legendDispatcher = d3.dispatch("cellover", "cellout", "cellclick");

    function legend(svg){

      var type = helper.d3_calcType(scale, cells, labels, labelFormat, labelDelimiter);

      var cell = svg.selectAll(".cell").data(type.data),
        cellEnter = cell.enter().append("g", ".cell").attr("class", "cell").style("opacity", 1e-6);
        shapeEnter = cellEnter.append(shape).attr("class", "swatch"),
        shapes = cell.select("g.cell " + shape);

      //add event handlers
      helper.d3_addEvents(cellEnter, legendDispatcher);

      cell.exit().transition().style("opacity", 0).remove();

      //creates shape
      if (shape === "line"){
        helper.d3_drawShapes(shape, shapes, 0, shapeWidth);
        shapes.attr("stroke-width", type.feature);
      } else {
        helper.d3_drawShapes(shape, shapes, type.feature, type.feature, type.feature, path);
      }

      helper.d3_addText(svg, cellEnter, type.labels)

      //sets placement
      var text = cell.select("text"),
        shapeSize = shapes[0].map(
          function(d, i){
            var bbox = d.getBBox()
            var stroke = scale(type.data[i]);

            if (shape === "line" && orient === "horizontal") {
              bbox.height = bbox.height + stroke;
            } else if (shape === "line" && orient === "vertical"){
              bbox.width = bbox.width;
            }

            return bbox;
        });

      var maxH = d3.max(shapeSize, function(d){ return d.height + d.y; }),
      maxW = d3.max(shapeSize, function(d){ return d.width + d.x; });

      var cellTrans,
      textTrans,
      textAlign = (labelAlign == "start") ? 0 : (labelAlign == "middle") ? 0.5 : 1;

      //positions cells and text
      if (orient === "vertical"){

        cellTrans = function(d,i) {
            var height = d3.sum(shapeSize.slice(0, i + 1 ), function(d){ return d.height; });
            return "translate(0, " + (height + i*shapePadding) + ")"; };

        textTrans = function(d,i) { return "translate(" + (maxW + labelOffset) + "," +
          (shapeSize[i].y + shapeSize[i].height/2 + 5) + ")"; };

      } else if (orient === "horizontal"){
        cellTrans = function(d,i) {
            var width = d3.sum(shapeSize.slice(0, i + 1 ), function(d){ return d.width; });
            return "translate(" + (width + i*shapePadding) + ",0)"; };

        textTrans = function(d,i) { return "translate(" + (shapeSize[i].width*textAlign  + shapeSize[i].x) + "," +
              (maxH + labelOffset ) + ")"; };
      }

      helper.d3_placement(orient, cell, cellTrans, text, textTrans, labelAlign);
      cell.transition().style("opacity", 1);

    }



  legend.scale = function(_) {
    if (!arguments.length) return legend;
    scale = _;
    return legend;
  };

  legend.cells = function(_) {
    if (!arguments.length) return legend;
    if (_.length > 1 || _ >= 2 ){
      cells = _;
    }
    return legend;
  };


  legend.shape = function(_, d) {
    if (!arguments.length) return legend;
    if (_ == "rect" || _ == "circle" || _ == "line" ){
      shape = _;
      path = d;
    }
    return legend;
  };

  legend.shapeWidth = function(_) {
    if (!arguments.length) return legend;
    shapeWidth = +_;
    return legend;
  };

  legend.shapePadding = function(_) {
    if (!arguments.length) return legend;
    shapePadding = +_;
    return legend;
  };

  legend.labels = function(_) {
    if (!arguments.length) return legend;
    labels = _;
    return legend;
  };

  legend.labelAlign = function(_) {
    if (!arguments.length) return legend;
    if (_ == "start" || _ == "end" || _ == "middle") {
      labelAlign = _;
    }
    return legend;
  };

  legend.labelFormat = function(_) {
    if (!arguments.length) return legend;
    labelFormat = _;
    return legend;
  };

  legend.labelOffset = function(_) {
    if (!arguments.length) return legend;
    labelOffset = +_;
    return legend;
  };

  legend.labelDelimiter = function(_) {
    if (!arguments.length) return legend;
    labelDelimiter = _;
    return legend;
  };

  legend.orient = function(_){
    if (!arguments.length) return legend;
    _ = _.toLowerCase();
    if (_ == "horizontal" || _ == "vertical") {
      orient = _;
    }
    return legend;
  };

  d3.rebind(legend, legendDispatcher, "on");

  return legend;

};


},{"./legend":2}],4:[function(require,module,exports){
var helper = require('./legend');

module.exports = function(){

  var scale = d3.scale.linear(),
    shape = "path",
    shapeWidth = 15,
    shapeHeight = 15,
    shapeRadius = 10,
    shapePadding = 5,
    cells = [5],
    labels = [],
    useClass = false,
    labelFormat = d3.format(".01f"),
    labelAlign = "middle",
    labelOffset = 10,
    labelDelimiter = "to",
    orient = "vertical",
    legendDispatcher = d3.dispatch("cellover", "cellout", "cellclick");

    function legend(svg){

      var type = helper.d3_calcType(scale, cells, labels, labelFormat, labelDelimiter);

      var cell = svg.selectAll(".cell").data(type.data),
        cellEnter = cell.enter().append("g", ".cell").attr("class", "cell").style("opacity", 1e-6);
        shapeEnter = cellEnter.append(shape).attr("class", "swatch"),
        shapes = cell.select("g.cell " + shape);

      //add event handlers
      helper.d3_addEvents(cellEnter, legendDispatcher);

      //remove old shapes
      cell.exit().transition().style("opacity", 0).remove();

      helper.d3_drawShapes(shape, shapes, shapeHeight, shapeWidth, shapeRadius, type.feature);
      helper.d3_addText(svg, cellEnter, type.labels)

      // sets placement
      var text = cell.select("text"),
        shapeSize = shapes[0].map( function(d){ return d.getBBox(); });

      var maxH = d3.max(shapeSize, function(d){ return d.height; }),
      maxW = d3.max(shapeSize, function(d){ return d.width; });

      var cellTrans,
      textTrans,
      textAlign = (labelAlign == "start") ? 0 : (labelAlign == "middle") ? 0.5 : 1;

      //positions cells and text
      if (orient === "vertical"){
        cellTrans = function(d,i) { return "translate(0, " + (i * (maxH + shapePadding)) + ")"; };
        textTrans = function(d,i) { return "translate(" + (maxW + labelOffset) + "," +
              (shapeSize[i].y + shapeSize[i].height/2 + 5) + ")"; };

      } else if (orient === "horizontal"){
        cellTrans = function(d,i) { return "translate(" + (i * (maxW + shapePadding)) + ",0)"; };
        textTrans = function(d,i) { return "translate(" + (shapeSize[i].width*textAlign  + shapeSize[i].x) + "," +
              (maxH + labelOffset ) + ")"; };
      }

      helper.d3_placement(orient, cell, cellTrans, text, textTrans, labelAlign);
      cell.transition().style("opacity", 1);

    }


  legend.scale = function(_) {
    if (!arguments.length) return legend;
    scale = _;
    return legend;
  };

  legend.cells = function(_) {
    if (!arguments.length) return legend;
    if (_.length > 1 || _ >= 2 ){
      cells = _;
    }
    return legend;
  };

  legend.shapePadding = function(_) {
    if (!arguments.length) return legend;
    shapePadding = +_;
    return legend;
  };

  legend.labels = function(_) {
    if (!arguments.length) return legend;
    labels = _;
    return legend;
  };

  legend.labelAlign = function(_) {
    if (!arguments.length) return legend;
    if (_ == "start" || _ == "end" || _ == "middle") {
      labelAlign = _;
    }
    return legend;
  };

  legend.labelFormat = function(_) {
    if (!arguments.length) return legend;
    labelFormat = _;
    return legend;
  };

  legend.labelOffset = function(_) {
    if (!arguments.length) return legend;
    labelOffset = +_;
    return legend;
  };

  legend.labelDelimiter = function(_) {
    if (!arguments.length) return legend;
    labelDelimiter = _;
    return legend;
  };

  legend.orient = function(_){
    if (!arguments.length) return legend;
    _ = _.toLowerCase();
    if (_ == "horizontal" || _ == "vertical") {
      orient = _;
    }
    return legend;
  };

  d3.rebind(legend, legendDispatcher, "on");

  return legend;

};


},{"./legend":2}],5:[function(require,module,exports){
d3.legend = {
  color: require('./color'),
  size: require('./size'),
  symbol: require('./symbol')
};
},{"./color":1,"./size":3,"./symbol":4}]},{},[5]);



   legend code ending here

我使用以下代码

       <!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>D3 Example</title>
    <script src="d3.min.js"></script>
    <script src="d3-legend.js"></script>
<meta name="viewport" content="width=device-width" />
    <link href='https://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
    <style>
    body { font: 12px Arial;}

 path { 
  stroke: steelblue;
  stroke-width: 2;
  fill: none;
 }
      .axis text {
        font-family: 'Open Sans', sans-serif;
        font-size: 12pt;
      }
      .axis .label {
        font-size: 20pt;
      }

      .axis path, .axis line {
        fill: none;
        stroke: #000;
        shape-rendering: crispEdges;
      }

      .color-legend text {
        font-family: 'Open Sans', sans-serif;
        font-size: 12pt;
      }

rect:hover {
    fill: #3EBCE6;
   }
.toolTip {
    font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
    position: absolute;
    display: none;
    width: auto;
    height: auto;
    background: none repeat scroll 0 0 white;
    border: 0 none;
    border-radius: 8px 8px 8px 8px;
    box-shadow: -3px 3px 15px #888888;
    color: black;
    font: 12px sans-serif;
    padding: 5px;
    text-align: center;
}

    </style>
  </head>
  <body>


    <script>


      var outerWidth = window.innerWidth-30;
      var outerHeight = window.innerHeight-80;
      var margin = { left: 50, top: 30, right: 30, bottom: 40 };

      var barPadding = 0.2;

      var xColumn = "Building";
      var yColumn = "Total";
      var colorColumn = "Type";
      var layerColumn = colorColumn;


      var innerWidth  = outerWidth- margin.left - margin.right;
      var innerHeight = outerHeight- margin.top  - margin.bottom;

      var svg = d3.select("body").append("svg")
     .attr("width",  outerWidth)
        .attr("height", outerHeight+50);
      var g = svg.append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.right + ")");
      var xAxisG = g.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate(0," + innerHeight + ")");
      var yAxisG = g.append("g")
        .attr("class", "y axis");
      var colorLegendG = g.append("g")
        .attr("class", "color-legend")
        .attr("transform", "translate("+(outerWidth-200)+", 0)");


    debugger;
      var xScale = d3.scale.ordinal().rangeBands([0, innerWidth-150], barPadding);
      var yScale = d3.scale.linear().range([innerHeight, 0]);
      var colorScale = d3.scale.category10();

      var xAxis = d3.svg.axis().scale(xScale).orient("bottom")
        .outerTickSize(0);
      var yAxis = d3.svg.axis().scale(yScale).orient("left")
        .ticks(7)
        .tickFormat(d3.format("s"))
        .outerTickSize(0);

      var colorLegend = d3.legend.color()
        .scale(colorScale)
        .shapePadding(2)
        .shapeWidth(15)
        .shapeHeight(15)
        .labelOffset(4);

      function render(data){

        var nested = d3.nest()
          .key(function (d){ return d[layerColumn]; })
          .entries(data)

        var stack = d3.layout.stack()
          .y(function (d){ return d[yColumn]; })
          .values(function (d){ return d.values; });

        var layers = stack(nested);





//tool tip for div class
var divTooltip = d3.select("body").append("div").attr("class", "toolTip");

        xScale.domain(layers[0].values.map(function (d){
          return d[xColumn];
        }));

        yScale.domain([
          0,
          d3.max(layers, function (layer){
            return d3.max(layer.values, function (d){
              return d.y;
            });
          })
        ]);

        colorScale.domain(layers.map(function (layer){
          return layer.key;
        }));

        xAxisG.call(xAxis)
  .selectAll("text")  
            .style("text-anchor", "end")
            .attr("dx", "-.5em")
            .attr("dy", "-.0em")

            .attr("transform", function(d) {
                return "rotate(-45)" 
                });
        yAxisG.call(yAxis);

        var layers = g.selectAll(".layer").data(layers);
        layers.enter().append("g").attr("class", "layer");
        layers.exit().remove();
        layers.style("fill", function (d){
          return colorScale(d.key);
        });

        var bars = layers.selectAll("rect").data(function (d){
          return d.values;
        });
        var barWidth = xScale.rangeBand() / colorScale.domain().length;
        bars.enter()
  .append("rect")
        bars.exit().remove();
        bars

          .attr("x", function (d, i, j){
            return xScale(d[xColumn]) + barWidth * j;
          })

          .attr("y", function (d){ return yScale(d.y); })
          .attr("width", barWidth)
          .attr("height", function (d){ return innerHeight - yScale(d.y); })


    //toolTip mouse hover on bar
    bars.on("mousemove", function(d){
        divTooltip.style("left", d3.event.pageX+10+"px");
        divTooltip.style("top", d3.event.pageY-25+"px");
        divTooltip.style("display", "inline-block");
        var x = d3.event.pageX,
  y = d3.event.pageY
        var elements = document.querySelectorAll(':hover');
        l = elements.length
        l = l-1
        elementData = function(d){return d}
        divTooltip.html((d.Building)+"<br>"+"Type:"+d.Type+"<br>"+"Small:"+d.Small+"<br>"+"Medium:"+d.Medium+"<br>"+"Large:"+d.Large+"<br>"+"Total:"+d.Total+"<br>");
    })
 //tooltip mouse release on bar
 bars.on("mouseout", function(d){
        divTooltip.style("display", "none");
    })




 //legend
   .text(function(d) {
         return d.VALUE;
         });
        colorLegendG.call(colorLegend);
     //resize                   
                    window.onresize = function () {
                    debugger;
                    // new width
                    var width = window.innerWidth;
                    svg.attr("width", width);

                    // new x scale
                    xScale = d3.scale.ordinal().rangeBands([0, width], 0.2);
                    // update x axis
                   xAxis = d3.svg.axis()
                                      .scale(xScale)
                                      .orient("bottom")
                                      .ticks(10);
                    svg.select(".x.axis")
                        .transition()
                        .duration(5000)
                        .call(xAxis);
                    // update bars

                }
      }

      function type(d){

        d.Total = +d.Total;
        return d;
      }

      d3.csv("D3.csv", type, render);




// Define the div for the tooltip


    </script>

  </body>
</html>

这里我添加了我的csv文件

Building,Type,Small,Medium,Large,Total
Building1,Food,18,38,40,96
Building1,Medicine,24,38,24,86
Building2,Food,31,24,40,95
Building2,Medicine,17,38,22,77
Building3,Food,24,24,22,70
Building3,Medicine,27,38,40,105
Building4,Food,23,38,24,85
Building4,Medicine,20,38,22,80
Building5,Food,17,24,40,81
Building5,Medicine,40,38,22,100
Building6,Food,18,38,40,96
Building6,Medicine,24,38,24,86
Building7,Food,31,24,40,95
Building7,Medicine,17,38,22,77
Building8,Food,24,24,22,70
Building8,Medicine,27,38,40,105

但这不适合我。当我按下刷新按钮然后只有它会调整大小才能解决我的问题

2 个答案:

答案 0 :(得分:3)

使用以下代码触发图表调整

        window.onresize = function(){ //logic to resize the chart }

        window.onresize = myFunction;

根据要求,我修改了图表代码。这是更新的html文件:

        <!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>D3 Example</title>
  <script src="https://d3js.org/d3.v3.min.js"></script>
  <script src="d3-legend.js"></script>
  <meta name="viewport" content="width=device-width"/>
  <link href='https://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
  <style>
    body {
      font: 12px Arial;
    }

    path {
      stroke: steelblue;
      stroke-width: 2;
      fill: none;
    }

    .axis text {
      font-family: 'Open Sans', sans-serif;
      font-size: 12pt;
    }

    .axis .label {
      font-size: 20pt;
    }

    .axis path, .axis line {
      fill: none;
      stroke: #000;
      shape-rendering: crispEdges;
    }

    .color-legend text {
      font-family: 'Open Sans', sans-serif;
      font-size: 12pt;
    }

    rect:hover {
      fill: #3EBCE6;
    }

    .toolTip {
      font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
      position: absolute;
      display: none;
      width: auto;
      height: auto;
      background: none repeat scroll 0 0 white;
      border: 0 none;
      border-radius: 8px 8px 8px 8px;
      box-shadow: -3px 3px 15px #888888;
      color: black;
      font: 12px sans-serif;
      padding: 5px;
      text-align: center;
    }
  </style>
</head>
<body>

<script>

  var svg = d3.select("body").append("svg");
  var margin = {left: 50, top: 30, right: 30, bottom: 40};

  var barPadding = 0.2;

  var xColumn = "Building";
  var yColumn = "Total";
  var colorColumn = "Type";
  var xAxisShift = 150;
  var layerColumn, xScale, yScale, xAxisG, yAxisG, colorLegendG, xAxis, yAxis, g;
  var colorScale = d3.scale.category10();
  var colorLegend = d3.legend.color()
    .scale(colorScale)
    .shapePadding(2)
    .shapeWidth(15)
    .shapeHeight(15)
    .labelOffset(4);


  function recalculateDimensions() {
    var outerWidth = window.innerWidth - 30;
  var outerHeight = window.innerHeight - 80;
  layerColumn = colorColumn;


  var innerWidth = outerWidth - margin.left - margin.right;
  var innerHeight = outerHeight - margin.top - margin.bottom;


    svg.attr("width", outerWidth)
    .attr("height", outerHeight + 50);
  g = svg.append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.right + ")");
  xAxisG = g.append("g")
    .attr("class", "x axis")
    .attr("transform", "translate(0," + innerHeight + ")");
  yAxisG = g.append("g")
    .attr("class", "y axis");
  colorLegendG = g.append("g")
    .attr("class", "color-legend")
    .attr("transform", "translate(" + (outerWidth - 200) + ", 0)");


  xScale = d3.scale.ordinal().rangeBands([0, innerWidth - xAxisShift], barPadding);
  yScale = d3.scale.linear().range([innerHeight, 0]);

  xAxis = d3.svg.axis().scale(xScale).orient("bottom")
    .outerTickSize(0);
  yAxis = d3.svg.axis().scale(yScale).orient("left")
    .ticks(7)
    .tickFormat(d3.format("s"))
    .outerTickSize(0);


  }

  recalculateDimensions();

  function render(data) {

    var nested = d3.nest()
      .key(function (d) {
        return d[layerColumn];
      })
      .entries(data)

    var stack = d3.layout.stack()
      .y(function (d) {
        return d[yColumn];
      })
      .values(function (d) {
        return d.values;
      });

    var layers = stack(nested);


//tool tip for div class
    var divTooltip = d3.select("body").append("div").attr("class", "toolTip");

    xScale.domain(layers[0].values.map(function (d) {
      return d[xColumn];
    }));

    yScale.domain([
      0,
      d3.max(layers, function (layer) {
        return d3.max(layer.values, function (d) {
          return d.y;
        });
      })
    ]);

    colorScale.domain(layers.map(function (layer) {
      return layer.key;
    }));

    xAxisG.call(xAxis)
      .selectAll("text")
      .style("text-anchor", "end")
      .attr("dx", "-.5em")
      .attr("dy", "-.0em")

      .attr("transform", function (d) {
        return "rotate(-45)"
      });
    yAxisG.call(yAxis);

    var layers = g.selectAll(".layer").data(layers);
    layers.enter().append("g").attr("class", "layer");
    layers.exit().remove();
    layers.style("fill", function (d) {
      return colorScale(d.key);
    });

    var bars = layers.selectAll("rect").data(function (d) {
      return d.values;
    });
    var barWidth = xScale.rangeBand() / colorScale.domain().length;
    bars.enter()
      .append("rect")
    bars.exit().remove();
    bars

      .attr("x", function (d, i, j) {
        return xScale(d[xColumn]) + barWidth * j;
      })

      .attr("y", function (d) {
        return yScale(d.y);
      })
      .attr("width", barWidth)
      .attr("height", function (d) {
        return innerHeight - yScale(d.y) - xAxisShift;
      })


    //toolTip mouse hover on bar
    bars.on("mousemove", function (d) {
      divTooltip.style("left", d3.event.pageX + 10 + "px");
      divTooltip.style("top", d3.event.pageY - 25 + "px");
      divTooltip.style("display", "inline-block");
      var x = d3.event.pageX,
        y = d3.event.pageY
      var elements = document.querySelectorAll(':hover');
      l = elements.length
      l = l - 1
      elementData = function (d) {
        return d
      }
      divTooltip.html((d.Building) + "<br>" + "Type:" + d.Type + "<br>" + "Small:" + d.Small + "<br>" + "Medium:" + d.Medium + "<br>" + "Large:" + d.Large + "<br>" + "Total:" + d.Total + "<br>");
    })
    //tooltip mouse release on bar
    bars.on("mouseout", function (d) {
      divTooltip.style("display", "none");
    })




    //legend
      .text(function (d) {
        return d.VALUE;
      });
    colorLegendG.call(colorLegend);
  }

  function type(d) {

    d.Total = +d.Total;
    return d;
  }

  d3.csv("D3.csv", type, function(data){
    chartData = data;
    render(chartData);
  });


  // Define the div for the tooltip
window.onresize = function () {
      d3.select('svg>g').remove();
      recalculateDimensions();
        render(chartData);
}

</script>

</body>
</html>

首选解决方案是使用如下所示的svg,这样可以立即响应

    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 525 365" preserveAspectRatio="xMidYMin slice"></svg>

答案 1 :(得分:0)

函数必须返回一些东西才能工作。 myFunction()仅捕获窗口内部高度和宽度,但不返回它。 用你的功能替换它:

function myFunction() {
     var m = new Array();
     m['w'] = window.outerWidth;
     m['h'] = window.outerHeight;
     return m;

}

然后得到这样的值:

var m = myFunction();
currentWidth = m['w'];
currentHeight = m['h'];

如果这不是您要找的内容,请告诉我