我正在使用Matt Kohl的动画圆环图在我网站上的元素中使用,我已经重新设计了它,但无法弄清楚如何将它重新定位到我想要的任何位置。它固定在浏览器窗口的中间。
不是将所有代码放在这里,而是在他的教程中给你一个代码链接:
https://bl.ocks.org/mattkohl/9f3a283813cf0226311f41595582c9eb
我已经尝试过HTML和CSS中的所有内容来操纵容器svg的大小和图表的位置,但无济于事。
显然需要在JavaScript中改变一些东西,但我不是专家,所以我想在这里问一下。
答案 0 :(得分:0)
以下是要查看的相关代码。 width和height变量将控制使用.attr("width", width)
和.attr("height", height)
传入的svg大小。现在更好地定位svg,我会给它一个类或id,如下所示。然后,您可以使用css定位将svg定位到所需的位置。
var duration = 1500,
transition = 200,
percent = 45,
width = window.innerWidth - 20,
height = window.innerHeight - 20;
var dataset = {
lower: calcPercent(0),
upper: calcPercent(percent)
},
radius = Math.min(width, height) / 3,
pie = d3.layout.pie().sort(null),
format = d3.format(".0%");
var arc = d3.svg.arc()
.innerRadius(radius * .8)
.outerRadius(radius);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.attr("id", "yourid")
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
#yourid{position: absolute;top:50%;}

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Animated Donut with Percentage</title>
<style type="text/css">
@import url(https://fonts.googleapis.com/css?family=Open+Sans);
body {
width: 100%;
height: 100%;
font-family: Lora,"Helvetica Neue",Helvetica,Arial,sans-serif;
color: #fff;
background-color: #000;
}
path.color0 {
fill: #fff;
}
path.color1 {
fill: rgba(255,255,255,.3);
}
text {
font-size: 7em;
font-weight: 400;
line-height: 16em;
fill: #fff;
}
</style>
</head>
<body>
<script src="https://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script type="text/javascript">
var duration = 1500,
transition = 200,
percent = 45,
width = 300,
height = 300;
var dataset = {
lower: calcPercent(0),
upper: calcPercent(percent)
},
radius = Math.min(width, height) / 3,
pie = d3.layout.pie().sort(null),
format = d3.format(".0%");
var arc = d3.svg.arc()
.innerRadius(radius * .8)
.outerRadius(radius);
var svg = d3.select("body").append("svg")
.attr("id", "yourid")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
var path = svg.selectAll("path")
.data(pie(dataset.lower))
.enter().append("path")
.attr("class", function (d, i) {
return "color" + i
})
.attr("d", arc)
.each(function (d) {
this._current = d;
});
var text = svg.append("text")
.attr("text-anchor", "middle")
.attr("dy", ".3em");
var progress = 0;
var timeout = setTimeout(function () {
clearTimeout(timeout);
path = path.data(pie(dataset.upper));
path.transition().duration(duration).attrTween("d", function (a) {
var i = d3.interpolate(this._current, a);
var i2 = d3.interpolate(progress, percent)
this._current = i(0);
return function (t) {
text.text(format(i2(t) / 100));
return arc(i(t));
};
});
}, 200);
function calcPercent(percent) {
return [percent, 100 - percent];
};
</script>
&#13;
附加的片段将更改与大小和位置的虚拟值放在一起。