如何使 D3 图表响应式?



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

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');

svgalement 中删除widthheight属性。

添加.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 + ")");

最新更新