Billboardjs chart bigger than it's container

2019-08-25 11:24发布

When generating a billboard chart and not providing a size, sometime the resulting svg is bigger than the container. Is there a way to make sure the svg size is always within bounds?

That is, without providing size in the generation config.

var chart = bb.generate({
    bindto: "#chart",
    data: {
        columns: [
            ["data1", 130, 200, 100, 170, 150, 250],
            ["data2", 130, 100, 140, 35, 110, 50]
        ],
        types: { 
          data1: "line",
          data2: "area-spline"
        },
        colors: {
          data1: "red",
          data2: "green"
        }
    }
});

setTimeout(() => {
  const containerW = $("#chart").width();
  const svgW = $("#chart svg").width();
  console.log(`div width - ${containerW}`);
  console.log(`SVG width - ${svgW}`);
});
#chart {
  width: 501px;
  height: 201px;
  border: 1px solid green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
    <html>
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width">
      <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/billboard.js/dist/billboard.min.css" />
      <script src="https://cdn.jsdelivr.net/npm/billboard.js/dist/billboard.pkgd.min.js"></script>
      <title>JS Bin</title>
    </head>
    <body>
     <div id="chart"></div> 
    </body>
    </html>

1条回答
萌系小妹纸
2楼-- · 2019-08-25 11:36

billboard.js is taking the dimension value from its parent node. Specifically, the offset values - node.offsetWidth/offsetHeight.

From your example, the parent <div> has the margin value. The jQuery's .width() returns without it.

So, according its process, it's setting correct dimension. If you need to handle with margin/padding values, you might put another parent wrapper for it.

<div id="wrapper">   // <-- set margin/padding if you need
    <div id="chart">
        <svg> ...

查看更多
登录 后发表回答