D3.js 鼠标事件

428 阅读1分钟

D3.js 鼠标事件

其实我们大家都比较熟悉js原生的鼠标事件,像鼠标点击/移动等事件,因为d3归根结底是操作的dom元素,所以一样是可以使用鼠标事件的,使用selection.on()这个API即可

1.点击事件Click mouseover mousemove mouseleave 鼠标移入移出事件

<body>
    <svg width="500" height="400" style="border: 1px solid red">
        <!-- <rect width="100" height="100" fill="red"></rect> -->
    </svg>
</body>

</html>
<script>
    const rect = d3.select('svg')    // 这一步是生成一个矩形元素
                    .append("rect")
                    .attr("width",100)
                    .attr("height",100)
                    .attr("fill","blue")
    rect.on("click",function () {    // 获取对应的rect元素
        d3.select(this)  // 这里的this是获取到的对应的rect元素
        .transition()  // 可以添加动画效果
        .duration(1000)
        .attr("x",200)
        .attr("y",100)
    })
  rect.on("mouseover",function() {
      d3.select(this)  // 这里的this是获取到的对应的rect元素
        .attr("fill","red")
})
rect.on("mouseleave",function () {
        d3.select(this)  // 这里的this是获取到的对应的rect元素
            .transition()
            .duration(1000)
            .attr("x", 0)
            .attr("y",0)
    })                    
</script>

11.gif

  1. d3.pointer(事件, target) 获取鼠标的x,y 坐标。
<body>
    <svg width="500" height="400" style="border: 1px solid red">
        <!-- <rect width="100" height="100" fill="red"></rect> -->
    </svg>
</body>

</html>
<script>
    const svg = d3.select('svg');

    svg.on("mousemove", function () {
        const xy = d3.pointer(event, svg.node());
        console.log(event);  // 获取事件
        console.log(svg.node());  // 获取svg元素的节点
        console.log(xy)  // 返还的数值是一个数组,返回x y坐标
    })
	
</script>

11.png

22.png

<body>
    <svg width="500" height="400" style="border: 1px solid red">
    </svg>
</body>

</html>
<script>
    const svg = d3.select('svg');
    const text = svg.append("text")
    svg.on("mousemove", function () {
        const xy = d3.pointer(event, event.target);
        text.attr('x', xy[0]) //取x的坐标
            .attr('y', xy[1]) //取y的坐标
            .text(`X:${parseInt(xy[0]) + 10},Y:${parseInt(xy[1])}`)
    })

</script>

22.gif

<body>
    <svg width="500" height="400" style="border: 1px solid red">
    </svg>
</body>

</html>
<script>
    const data = [30, 60, 110, 200]
    const dots = d3.select('svg').selectAll('circle')
        .data(data)
        .join('circle')
        .attr('cx', d => d)
        .attr('cy', (d, i) => (i + 1) * 50)
        .attr('r', '20')
        .attr('fill', 'blue')

    // 绑定事件
    dots.on('mouseover', function () {
        let pt = d3.pointer(event, event.target)
        d3.select(this)
            .attr('fill', 'red')
            .transition()
            .attr('cx', pt[0] + 100)
    });
</script>

33.gif