1

円がいくつかあるチャートがあります。ユーザーが円の上にカーソルを置いたときに、マウスオーバー イベントを作成し、その円の中心の x 座標と y 座標を渡したいと思います。それ、どうやったら出来るの?

svg.selectAll("circle") 
      .data(data)
      .enter().append("circle")
      .attr("cx", function(d) { return x(d.number); })
      .attr("cy", function(d) { return y(d.area); })
      .call(d3.my_helper.tooltip(function(d, i){return "Area: "+ d.area;}));

d3.my_helper.tooltip = function(accessor){
            return function(selection){
                var circle_x = ???; // the center of the circle
                var circle_y = ???; // the center of the circle
                selection.on("mouseover", function(d, i){
                    // do stuff here with circle_x and circle_y
                });
            };
        }; 
4

2 に答える 2

2

svg elem 自体のオフセットを見つけ、それに応じて「cy」属性 (中心 y) を y 座標に追加し、「cx」属性 (中心 x) を x 座標に追加する必要があります。

$('circle').hover(function (ev) {
    var svgPos = $('svg').offset(),
        x = svgPos.left + $(ev.target).attr('cx'),
        y = svgPos.top + $(ev.target).attr('cy'),
        coords = [x, y];

    // coords now has your coordinates
});

jQuery を使用していない場合は、通常のホバー イベント リスナーと要素の使用を検討して.offsetTopください.offsetLeft

于 2012-11-02T07:36:46.710 に答える