最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Parameters needed for d3.mouse() - Stack Overflow

programmeradmin7浏览0评论

I am trying to get mouse coordinates relative to a group element. Here's the code:

var backRect = chart.append("g").attr("class", "rect");
var g = backRect.append('rect')
        .style('stroke', 'none')
        .style('fill', '#FFF')
        .style('fill-opacity', 0)
        .attr({
            width: width,
            height: height,
            'pointer-events': 'none',
            'class': 'backRect'
        });

// the code below is inside another container's event; but I want mouse coordinates relative to the above rect, hence can't use d3.mouse(this)
// get mouse pointer location
        var coordinates = [0, 0];
        coordinates = d3.mouse(backRect); // d3.select(".rect") does not work either

but get the following error:

d3.min.js:1 Uncaught TypeError: n.getBoundingClientRect is not a function

According to the d3 mouse docs d3.mouse() takes a container which can be svg or g element.

What parameter should I pass to d3.mouse()? I tried d3.select(".rect") which is not working either.

I am trying to get mouse coordinates relative to a group element. Here's the code:

var backRect = chart.append("g").attr("class", "rect");
var g = backRect.append('rect')
        .style('stroke', 'none')
        .style('fill', '#FFF')
        .style('fill-opacity', 0)
        .attr({
            width: width,
            height: height,
            'pointer-events': 'none',
            'class': 'backRect'
        });

// the code below is inside another container's event; but I want mouse coordinates relative to the above rect, hence can't use d3.mouse(this)
// get mouse pointer location
        var coordinates = [0, 0];
        coordinates = d3.mouse(backRect); // d3.select(".rect") does not work either

but get the following error:

d3.min.js:1 Uncaught TypeError: n.getBoundingClientRect is not a function

According to the d3 mouse docs d3.mouse() takes a container which can be svg or g element.

What parameter should I pass to d3.mouse()? I tried d3.select(".rect") which is not working either.

Share Improve this question edited Nov 25, 2020 at 13:40 software_writer asked Jun 24, 2016 at 21:17 software_writersoftware_writer 4,49810 gold badges40 silver badges68 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 8

Using d3.mouse(backRect.node()) did the trick.

You should be using d3.mouse() inside an event to get the values relative to the passed container.

Check this block

http://bl.ocks/hlucasfranca/f133da4493553963e710

svg.on("click", function() {
          var coords = d3.mouse(this);
          ........
          ........
})
发布评论

评论列表(0)

  1. 暂无评论