重新调整大小时重绘SVG

leb*_*olo 5 javascript svg d3.js

我试图在d3内重新调整窗口大小的SVG图表,但没有使用viewBoxpreserveAspectRatio参数(我不喜欢他们如何处理文本).

我还试图在附加单个元素(不基于支持数据)时通过Bostock的建议坚持使用d3的数据绑定设计.

我有一些归结为这个(jsFiddle).但是,SVG元素的宽度/高度永远不会更新.

HTML

<div class="chart-container">
    <button class="user-option">Some User Options</button>
    <div class="svg-container"></div>
</div>
Run Code Online (Sandbox Code Playgroud)

使用Javascript

$(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
            });
}
Run Code Online (Sandbox Code Playgroud)

leb*_*olo 1

谢谢,我能够从您的所有答案中找到正确的解决方案!然而,这两个答案都无法在调整大小时更新 SVG并将变量保留svgg元素(以遵守边距约定)。我最终做了

// 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 + ")");
Run Code Online (Sandbox Code Playgroud)