我有一些行,我正在将它们作为一个组移动。是否有可能在转变发生时单独移动它们?
我用棍子男人做了一个小例子来展示案例。当他向右移动时,他应该移动一只手臂。但是手臂保持不动。
var mode = "Transition";
var bodySelection = d3.select("body");
var divButton = bodySelection.append("div");
var button = divButton.append("button")
.attr("id","button")
.text(mode);
var svg = bodySelection.append("svg")
.attr("width",800)
.attr("height",600)
.style("fill","red");
var chest = svg.append("line")
.attr("x1",100)
.attr("y1",100)
.attr("x2",100)
.attr("y2",50)
.attr("stroke-width", 2)
.attr("stroke", "black");
var legL = svg.append("line")
.attr("x1",100)
.attr("y1",100)
.attr("x2",80)
.attr("y2",130)
.attr("stroke-width", 2)
.attr("stroke", "black");
var legR = svg.append("line")
.attr("x1",100)
.attr("y1",100)
.attr("x2",120)
.attr("y2",130)
.attr("stroke-width", 2)
.attr("stroke", "black");
var head = svg.append("circle")
.attr("cx",100)
.attr("cy",35)
.attr("r",15)
.attr("fill","black");
var armL = svg.append("line")
.attr("x1",100)
.attr("y1",60)
.attr("x2",80)
.attr("y2",75)
.attr("stroke-width", 2)
.attr("stroke", "black")
.on('click', function(){
console.log('polyline click');
console.log(this.getAttribute('x2'));
});
var armR = svg.append("line")
.attr("x1",100)
.attr("y1",60)
.attr("x2",120)
.attr("y2",75)
.attr("stroke-width", 2)
.attr("stroke", "black");
var body = svg.selectAll("line,circle");
button.on("click", function() {
if(mode=="Transition")
{
moveBody(200);
moveArmL();
mode="Reset";
}
else if(mode=="Reset")
{
moveBody(0);
mode="Transition";
}
button.text(mode);
})
function moveBody(x)
{
body.transition()
.attr("transform", "translate(" + x + ",0)")
.duration(1000);
}
function moveArmL()
{
armL.transition()
.attr("x2",90)
.duration(500)
.transition()
.attr("x2",80)
.duration(500);
}
答案 0 :(得分:2)
要将整个身体元素移动到一起,首先将一个组添加到svg,如下所示:
var svg = bodySelection.append("svg")
.attr("width",800)
.attr("height",600)
.style("fill","red").append("g");
现在移动整个小组
function moveBody(x)
{
svg.transition()
.attr("transform", "translate(" + x + ",0)")
.duration(1000);
}
工作代码here
希望这有帮助!