2

我正在尝试在 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)") });
4

2 回答 2

5

可以在此处找到无需平移的通用缩放解决方案: 围绕中心点缩放

主意:

translate(-centerX*(factor-1), -centerY*(factor-1))
scale(factor)
于 2013-03-12T16:25:02.747 回答
4

您的mouseovermouseout事件将覆盖原来的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)") });
于 2012-06-28T13:57:50.003 回答