我正在尝试在d3中的窗口调整大小上重新绘制SVG图表,但没有使用viewBox
和preserveAspectRatio
参数(我不喜欢它们如何处理文本)。
在附加单个元素(不基于支持的数据)时,我还尝试通过Bostock的建议坚持d3的数据绑定设计。
我有一些归结为这一点(jsFiddle)。但是,SVG元素的宽度/高度永远不会更新。
<div class="chart-container">
<button class="user-option">Some User Options</button>
<div class="svg-container"></div>
</div>
$(window).on("resize", function () {
draw();
});
function draw() {
var container = d3.select('.chart-container');
var drawWidth = Math.round(0.80 * container.node().clientWidth);
var drawHeight = Math.round(drawWidth * (3 / 4)); // Fixing a 4/3 aspect ratio
/*
* Use an inner g element as the SVG canvas in order to set and forget margins.
* See http://bl.ocks.org/mbostock/3019563
*/
var margin = {
top: 10,
right: 30,
bottom: 50,
left: 40
};
var width = drawWidth - margin.left - margin.right;
var height = drawHeight - margin.top - margin.bottom;
var svg = container.select(".svg-container").selectAll('svg')
.data([0]) // Single data element to create SVG if it doesn't exist
.enter().append("svg")
.attr("width", drawWidth)
.attr("height", drawHeight)
.append("g")
.attr("class", "canvas")
// jsFiddle doesn't translate correctly, maybe because of frames???
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
console.debug(svg.node()); // null on resize???
// Add some random SVG element
svg.selectAll('rect')
.data([0]) // Single data element to create SVG if it doesn't exist
.enter().append('rect')
.attr({
x: 0,
y: 0,
width: drawWidth - margin.right - margin.left,
height: drawHeight - margin.bottom - margin.top
});
}
谢谢,我能够从您的所有答案中找到正确的解决方案!然而,无论答案是能够更新调整大小的SVG和保持svg
变量作为g
元素(坚持使用保证金约定)。我最终做了
// Create SVG element (if it doesn't exist)
var svg = container.select(".svg-container").selectAll('svg').data([null]);
svg.enter().append("svg");
svg.attr({width: drawWidth, height: drawHeight}); // apply to enter + update selections
// Create g element (if it doesn't exist) and remap the svg variable
svg = svg.selectAll(".canvas").data([null]);
svg.enter().append("g") // apply to enter selection only
.attr("class", "canvas")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句