Javascript:如何覆盖整个区域?

时间:2018-05-19 09:54:09

标签: javascript css d3.js svg

我是第一次使用SVG编写代码。我在javascript中创建了一个小程序。矩形不是从该区域的底部完美开始,仍然是浅蓝色条带。

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <style type="text/css">
    #graphicArea {
      width: 1400px;
      background: #a7def2;
    }
  </style>
</head>
<body>
  <div id="outer-wrapper">
    <div id="graphicArea"> </div>
  </div>
  <script src="https://d3js.org/d3.v5.min.js"></script>
  <script>
    var width = 1400;
    var height = 600;
    var graphic;
    var gocceAlSec = 7;
    graphic = d3.select("#graphicArea").append("svg")
      .attr("width", width)
      .attr("height", height)
      .attr("id", "graphic")
      .attr("overflow", "hidden");

    var dataset = [0];

    graphic.selectAll("rect")
      .data(dataset)
      .enter()
      .append("rect")
      .attr("x", 0)
      .attr("y", 600)
      .attr("width", 1400)
      .attr("height", 0)
      .style("fill", "blue")
      .transition()
      .duration(50000)
      .attr("height", 600)
      .attr("y", 0);

  </script>
</body>

1 个答案:

答案 0 :(得分:3)

您将背景颜色设置为<div>,因此您必须处理默认边距,填充,计算高度等...

更简单的方法是将背景颜色设置为SVG:

graphic = d3.select("#graphicArea").append("svg")
      .attr("width", width)
      .attr("height", height)
      .attr("id", "graphic")
      .style("background", "#a7def2")

以下是您更改的代码:

&#13;
&#13;
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
</head>
<body>
  <div id="outer-wrapper">
    <div id="graphicArea"> </div>
  </div>
  <script src="https://d3js.org/d3.v5.min.js"></script>
  <script>
    var width = 1400;
    var height = 600;
    var graphic;
    var gocceAlSec = 7;
    graphic = d3.select("#graphicArea").append("svg")
      .attr("width", width)
      .attr("height", height)
      .attr("id", "graphic")
      .style("background", "#a7def2")
      .attr("overflow", "hidden");

    var dataset = [0];

    graphic.selectAll("rect")
      .data(dataset)
      .enter()
      .append("rect")
      .attr("x", 0)
      .attr("y", 600)
      .attr("width", 1400)
      .attr("height", 0)
      .style("fill", "blue")
      .transition()
      .duration(50000)
      .attr("height", 600)
      .attr("y", 0);

    function makeRain() {

      for (var i = 0; i < gocceAlSec; i++) {
        startX = Math.random() * width,
          startY = Math.random() * 100 - 100,
          endX = startX;
        endY = height + 200;
        graphic.insert("circle")
          .attr("cx", startX)
          .attr("cy", startY)
          .attr("r", 2)
          .style("fill", "blue")
          .transition()
          .duration(2000)
          .attr("cx", endX + 100)
          .attr("cy", endY)
          .remove();
      };
    }

    d3.timer(makeRain, 100);
  </script>
</body>
&#13;
&#13;
&#13;

如果您想坚持使用<div>样式,可以尝试进行一些更改,例如max-heigh: 600px;

PS:因为这是你的第一个D3 / SVG代码(顺便说一下,赞一下),这里有一个提示:你不需要为rect选择一个输入,不仅因为它只是因为它只是一个但主要是因为数据毫无意义。只需将元素附加到容器中即可。