首页 > 解决方案 > 屏幕调整大小上的响应式 D3 甜甜圈图

问题描述

我已经制作了一个 D3 圆环图看起来响应,但我希望它在任何屏幕 (div) 调整大小时都能 100% 响应。这个想法是计算父 div 的对角线并使用它来更改半径、字体大小等。在下面的这种情况下,我使用了对角线但不是调整大小函数。

是否可以快速使用更改半径、字体大小、图例矩形大小的调整大小功能?如果它是条形图,调整大小功能将非常简单。在这种情况下,我想知道是否值得在每个 D3 图表中创建一个基础。如果我使用这个基础: http: //jsfiddle.net/radomer/zc8akt40/我可以更改代码以使我的图形响应吗?我猜,如果是的话,我将不得不更改基本代码,因为我在悬停时会丢失图表中的动画。

//Calculate the diagonal of the parent sreen div

console.log('width')
console.log(window.innerWidth);
console.log('height')
console.log(window.innerHeight);
console.log('final');
console.log(Math.sqrt(Math.pow(window.innerWidth,2) + Math.pow(window.innerHeight,2)));

var diagonal = Math.sqrt(Math.pow(window.innerWidth,2) + Math.pow(window.innerHeight,2))/5;

//Create the D3 chart

var margin = {top: 20, right: 20, bottom: 50, left: 20},
    width = parseInt(d3.select("#chart").style("width")) - margin.left - margin.right,
    height = parseInt(d3.select("#chart").style("width")) - margin.top - margin.bottom,
    r = diagonal,
    inner = diagonal/2,
    color= d3.scale.ordinal()
    .range(["#124", "#214183", "#3061c2",  "#4876d1", "#87a5e1", "#c5d4f1"]);
    
data = [{"label":"ONE", "value":194}, 
        {"label":"TWO", "value":567}, 
        {"label":"THREE", "value":1314},
        {"label":"FOUR", "value":793},
        {"label":"FIVE", "value":1929},
        {"label":"SIX", "value":1383}];

var total = d3.sum(data, function(d) {
    return d3.sum(d3.values(d));
});

 
 var svg = d3.select('#chart').append("svg:svg");
 var vis = svg.data([data])
         .attr("width", '100%')
         .attr("height", '100%')
         .attr('viewBox',(-width / 2 ) + ' ' + (-height/2) + ' '+width +' '+height)
         .attr('preserveAspectRatio','xMinYMin')


var textTop = vis.append("text")
    .attr("dy", ".35em")
    .style("text-anchor", "middle")
    .attr("class", "textTop")
    .text( "TOTAL" )
    .attr("y", -10),
textBottom = vis.append("text")
    .attr("dy", ".35em")
    .style("text-anchor", "middle")
    .attr("class", "textBottom")
    .text(total.toFixed(2) + "m")
    .attr("y", 10);

var arc = d3.svg.arc()
    .innerRadius(inner)
    .outerRadius(r);

var arcOver = d3.svg.arc()
    .innerRadius(inner + 5)
    .outerRadius(r + 5);
 
var pie = d3.layout.pie()
    .value(function(d) { return d.value; });
 
var arcs = vis.selectAll("g.slice")
    .data(pie)
    .enter()
        .append("svg:g")
            .attr("class", "slice")
            .on("mouseover", function(d) {
                d3.select(this).select("path").transition()
                    .duration(200)
                    .attr("d", arcOver)
                
                textTop.text(d3.select(this).datum().data.label)
                    .attr("y", -10);
                textBottom.text(d3.select(this).datum().data.value.toFixed(2))
                    .attr("y", 10);
            })
            .on("mouseout", function(d) {
                d3.select(this).select("path").transition()
                    .duration(100)
                    .attr("d", arc);
                
                textTop.text( "TOTAL" )
                    .attr("y", -10);
                textBottom.text(total.toFixed(2) + "m");
            });

arcs.append("svg:path")
    .attr("fill", function(d, i) { return color(i); } )
    .attr("d", arc);

var legend = svg.append("svg")
    .attr("class", "legend")
    //.attr("width", r)
    //.attr("height", r * 2)
    .selectAll("g")
    .data(data)
    .enter().append("g")
    .attr("transform", function(d, i) { return "translate(" + (r + 20) + "," + i * 20 + ")"; });

legend.append("rect")
    .attr("width", 18)
    .attr("height", 18)
    .style("fill", function(d, i) { return color(i); });

legend.append("text")
    .attr("x", 24)
    .attr("y", 9)
    .attr("dy", ".35em")
    .text(function(d) { return d.label; }); 
*{
  font-family: 'Roboto', sans-serif;
  text-transform:capitalize;
  margin: 0 auto;
  text-align:left;
}

body {
        font-family: "Roboto"!important;
        width: 100%;
        height: 400px;
        position: relative;
    }

 

.slice path {
    stroke: #fff;
    stroke-width: 1px;
}

.textTop {
    font-size: 12pt;
    fill: #bbb;
}

.textBottom {
    fill: #444;
    font-weight: bold;
    font-size: 18pt;
}

.top {
    border: 1px solid #bbb;
    color: #777;
    padding: 5px;
    text-decoration: none;
}

.top:hover {
    border: 1px solid #555;
    color: #333;
}
<script src="https://code.jquery.com/jquery-1.9.1.js"></script>
<script src="https://d3js.org/d3.v3.min.js"></script>

<div id="chart"></div>

标签: javascriptcssd3.js

解决方案


您可以使用标签中的viewBox属性svg创建一个独立于实际屏幕尺寸的坐标系,然后用于style="width: x%; "根据可用宽度调整图像大小(与 相同img,您只能使用高度/宽度中的一个来拥有另一个按纵横比调整)。

这是它的样子:

<svg id="scalesvg" viewBox="0 0 100 100">

和 CSS

#scalesvg { width: 20%; }

我现在有一个 100x100 的坐标系,我可以在其中使用从 0 到 100 的绝对坐标进行绘制。浏览器仍然会调整大小。

但是,它也会调整字体大小,因此您可能会想出改变字体大小的媒体查询,并可能将文本向上/向下翻译几个像素,以真正创造良好的体验。

我发现了一篇很棒的博客文章,解释了所有细节(不是我的 - 赞美是因为谁写和分享了它): http: //www.sarasoueidan.com/blog/svg-coordinate-systems/

另外:您可以在这里找到我的试驾 codepen(更改浏览器窗口大小以进行测试):https ://codepen.io/sebredhh/pen/jvJGry


推荐阅读