如何使D3图表具有响应性?

时间:2018-10-12 09:06:49

标签: javascript d3.js charts

我需要使我的d3 js图表具有响应性,即在用户调整窗口大小时缩放图表。我尝试了svg的属性“ viewbox”和“ preserveaspectratio”,但是没有运气。这是我的fiddle

var svg = d3.select("#chart1").append("svg")
    .call(zoom)
    .attr("class", "chart")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom);
    .attr('viewBox','0 0 '+Math.min(pWidth,height)+'       '+Math.min(pWidth,height))
.attr('preserveAspectRatio','xMinYMin');

1 个答案:

答案 0 :(得分:0)

width元素中删除heightsvg属性。

添加.attr('preserveAspectRatio','xMinYMin');.attr("viewBox", '0 0 ' + width + ' ' + height)

相关代码:

var svg = d3.select("#chart1").append("svg")
.attr("preserveAspectRatio", "xMinYMin meet")
.attr("viewBox", '0 0 ' + width + ' ' + height)
    .call(zoom)
    .attr("class", "chart")
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");