我正在尝试在SVG和d3中使用scale()变换。我理解它通过增加坐标比例来工作,但它似乎也在翻译我的对象。当我有一个位于(100,100)的矩形并且我做一个比例(2)时,矩形的大小加倍并移动到(0,0)。如何缩放时让它停止从(100,100)移动到(0,0)。以下是我的代码:
var mysvg = d3.select("#viz")
.append("svg")
.attr("width", 500)
.attr("height", 500)
.attr("class","mylist");
var node = mysvg.selectAll("g.node")
.data(mydata)
.enter().append("g")
.attr("class","node")
.attr("transform", function(d) { return "translate(" + d.xpos + "," + d.ypos + ")"; });
node.append("rect")
.attr("width",tileWidth)
.attr("height",tileWidth)
.attr("fill","orange")
.attr("rx",10)
.attr("ry",10);
node.append("text")
.attr("transform",function(d) { return "translate(" + tileWidth/2 + "," + tileWidth/2 +")" })
.attr("text-anchor", "middle")
.attr("dy", ".3em")
.attr("font-family","serif")
.text(function(d) { return d.symbol; });
node.on("mouseover",function(){ d3.select(this).transition().attr("transform","scale(1.2)") });
node.on("mouseout",function(){ d3.select(this).transition().attr("transform","scale(1)") });
答案 0 :(得分:4)
您的mouseover
和mouseout
事件覆盖原始translate(" + d.xpos + "," + d.ypos + ")
。
我认为解决此问题的最简单方法是添加父g
并进行翻译,例如......
var mysvg = d3.select("#viz")
.append("svg")
.attr("width", 500)
.attr("height", 500)
.attr("class","mylist");
var parent = mysvg.selectAll("g.parent")
.data(mydata)
.enter().append("g")
.attr("class","parent")
.attr("transform", function(d) { return "translate(" + d.xpos + "," + d.ypos + ")"; });
var node = mysvg.selectAll("g.parent")
.enter().append("g")
.attr("class","node")
});
node.append("rect")
.attr("width",tileWidth)
.attr("height",tileWidth)
.attr("fill","orange")
.attr("rx",10)
.attr("ry",10);
node.append("text")
.attr("transform",function(d) { return "translate(" + tileWidth/2 + "," + tileWidth/2 +")" })
.attr("text-anchor", "middle")
.attr("dy", ".3em")
.attr("font-family","serif")
.text(function(d) { return d.symbol; });
node.on("mouseover",function(){ d3.select(this).transition().attr("transform","scale(1.2)") });
node.on("mouseout",function(){ d3.select(this).transition().attr("transform","scale(1)") });
答案 1 :(得分:4)
这里可以找到无需翻译的一般解决方案: Scaling Around a Center Point
点子:
translate(-centerX*(factor-1), -centerY*(factor-1))
scale(factor)