2016-01-13 36 views
2

我想拖動d3中的一組元素,但是當鼠標放在操作符上時,我還需要縮放組。D3轉換比例並保持位置不變

當我縮放組時,它會改變它的位置,是否可以縮放它,而它的位置在svg中是不變的?我的工作是fiddle

<svg width="400" height="400" style="background-color: red"> 

    <g id="op" class="operator"> 

     <circle cx="50" cy="50" r="20" style="fill: yellow"></circle> 

    </g> 

</svg> 

的script.js

d3.selectAll('.operator') 
     .on('mouseenter', function() { 

      console.log('Mouse Enter'); 
      d3.select(this).attr('transform', 'scale(2)'); 

     }) 
     .on('mouseleave', function() { 

      console.log('Mouse Leave'); 

     }) 
     .call(d3.behavior.drag() 
     .on('drag', function() { 

      d3.select(this).attr('transform', 'translate(' +       d3.event.x + ',' + d3.event.y + ')'); 

     }) 

     ) 

回答

2

當你這樣做的2

規模如果CX爲50和cy是50,然後在秤2圓將出現在center cx * scale = 100和cy * scale = 100。

這就是它在規模上跳躍的原因。現在如果你想圓是在同一個地方,你需要做的是這樣的:

d3.select(this).select("circle").attr("cx", 50/scale) 
d3.select(this).select("circle").attr("cy", 50/scale) 

除以規模,這將抵消爲圓心的規模效應。

所以後縮放的新Cx和Cy將是25

工作代碼here

+0

那麼,我的實際實施有組內的幾個圈子。我應該爲所有元素設置中心嗎? – Fawzan

+0

如果您將鼠標懸停在圓上,那麼您將不得不重置cx和cy,使其保持在相同的位置。 – Cyril

+0

指出。但我仍然在尋找一個簡單的解決方案。 :D – Fawzan