我正在尝试改编 Jeremy Stucki 的“Animated Flowers” block
http://bl.ocks.org/herrstucki/6199768/23f51b97bd942f6b1b7cf0b9ba76ada4cb6d1cc7
根据我为每个花瓣的大小提供的数据创建一朵非动画花。
我使用此 fiddle 中的脚本生成的数据创建一朵花: https://jsfiddle.net/NovasTaylor/f91ujcfp/
花瓣的数量应基于所提供的数据 (myPetalData) 中的行数 - 这应该相对容易。
var myPetalData = [
{id:0, size:1, petLen:1, petWid:0.25},
{id:1, size:2, petLen:1, petWid:0.5},
{id:2, size:2.5, petLen:1, petWid:0.6},
{id:3, size:5, petLen:1, petWid:1.0}
]
我的主要问题是如何为单个花瓣的构建提供数据(我仍在学习 Javascript 和 D3)。 花瓣可以基于 myPetalsData 中指定的“大小”变量,或者理想情况下是长度和宽度变量 petLen、petWid 的组合。大小或长度+宽度应编码为 D3Scales 以适应真实世界的数据。我还希望删除网格依赖性,除非花瓣构造需要它。
对于基本掌握 Javascript 和 D3 的人来说,这应该是一件容易的事。我很感激任何建议或更新的 fiddle ,让我沿着正确的道路前进。
谢谢!
蒂姆
最佳答案
也许是这样的
var width = 500,
height = 500,
halfRadius = 50; // length of petal & therefore size of digram overall
var size = d3.scale.sqrt()
.domain([0, 1])
.range([0, halfRadius]);
var myPetalData = [
{id:0, size:1},
{id:1, size:2},
{id:2, size:2.5},
{id:3, size:.1}
]
var pie = d3.layout.pie()
.sort(null)
.value(function(d) { return d.size; });
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width/2 + "," + height/2 + ")");
var petal = svg.selectAll(".petal")
.data(pie(myPetalData))
.enter().append("path")
.attr("class", "petal")
.attr("transform", function(d) { return r((d.startAngle + d.endAngle) / 2); })
.attr("d", petalPath)
.style("stroke", petalStroke)
.style("fill", petalFill);
function petalPath(d) {
var angle = (d.endAngle - d.startAngle) / 2,
s = polarToCartesian(-angle, halfRadius),
e = polarToCartesian(angle, halfRadius),
r = size(d.data.size),
m = {x: halfRadius + r, y: 0},
c1 = {x: halfRadius + r / 2, y: s.y},
c2 = {x: halfRadius + r / 2, y: e.y};
return "M0,0L" + s.x + "," + s.y + "Q" + c1.x + "," + c1.y + " " + m.x + "," + m.y + "L" + m.x + "," + m.y + "Q" + c2.x + "," + c2.y + " " + e.x + "," + e.y + "Z";
};
function petalFill(d, i) {
return d3.hcl(i / myPetalData.length * 360, 60, 70);
};
function petalStroke(d, i) {
return d3.hcl(i / myPetalData.length * 360, 60, 40);
};
function r(angle) {
return "rotate(" + (angle / Math.PI * 180) + ")";
}
function polarToCartesian(angle, radius) {
return {
x: Math.cos(angle) * radius,
y: Math.sin(angle) * radius
};
};
请注意,我将饼图居中,并删除了 petLen/petWid,因为我不清楚您期望这些与花瓣大小有何关系......
关于javascript - D3JS 花瓣/花图。如何适应使用数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46607640/