d3轴未按范围缩放

时间:2018-09-02 18:22:53

标签: javascript d3.js svg responsive-design

我正在尝试在d3中创建一个响应图。 这是代码片段:

<!DOCTYPE html>
<html>
<head>
</head>
<body>
    <div id="container" class="svg_container">
    </div>
</body>
<style>
    #container{
    width: 90%;
    height: 50vh;
    margin: auto;
    border: 1px solid red;
    }
</style>
<script src='https://d3js.org/d3.v4.min.js'></script>
<script>



    var width = 800,
        height = 425,
        aspect = width / height;

    console.log(width,height,aspect);
    var margin= 20;
    var canvas = d3.select("#container")
                   .append("svg")
                   .attr("width", width)
                   .attr("height", height)
                   .attr("viewBox", "0 0 " + width + " " + height)
                   .attr("preserveAspectRatio", "xMinYMid")
                   .style("border","1px solid black");

    var g = canvas.append("g")
                  .attr("transform", "translate(" + margin+ "," + margin + ")");                   



    window.addEventListener("load", resize);
    window.addEventListener("resize", resize);


    var x = d3.scaleLinear()
              .domain([0,25]);

    var xAxis = d3.axisBottom()
                .scale(x);  

    var xg = g.append("g")
              .attr("class", "x axis")
              .call(xAxis);         




    function resize(){
        d3.csv("time.csv", data =>{
        var targetWidth= document.getElementById("container").offsetWidth;

        var targetHeight = targetWidth/aspect;

        canvas.attr("width", targetWidth);
        canvas.attr("height", targetHeight);

        x.range([0, targetWidth]);
        xAxis.scale(x);

        console.log(targetWidth, x.range());

        xg.call(xAxis);

        });
    }

</script>
</html>

This是小提琴 但是,虽然svg和轴均响应,但轴似乎尺寸不正确。 (Console.log(x.range())显示的范围等于(响应的)宽度,但是生成的轴似乎不是这样。

0 个答案:

没有答案