2012-06-28 129 views
2

我試圖在SVG和d3中使用scale()轉換。我理解它通過增加座標尺度來工作,但它似乎也在翻譯我的對象。當我有一個矩形位於(100,100)並且我做一個比例(2)時,矩形的大小加倍並移動到(0,0)。如何在縮放時停止從(100,100)移動到(0,0)。下面是我的代碼:使用d3 SVG縮放而不翻譯

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

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)") }); 
+0

你可以添加一個完整的例子(的jsfiddle等),請? –

+0

@IonicăBizău您可以自己創建並與我聯繫,如果您遇到任何問題。 – Duopixel