d3js精通教程
In the last article we learned about fundamentals of D3js such as selections, DOM Manipulation, SVG, Scales and data binding. If you are getting started with D3js, I highly recommend reading that article first and then come back here.
在上一篇文章中,我们了解了D3js的基础知识,例如选择,DOM操作,SVG,Scales和数据绑定。 如果您开始使用D3js,我强烈建议您先阅读该文章 ,然后再回到这里。
Lets dive into the world of Interactivity, Data Manipulation and Layouts in this article.
在本文中,我们将深入探讨“ 交互性” ,“ 数据处理和布局 ”领域。
事件处理 (Event Handling)
Events can be attached by calling .on(event, function)
on selection element and by passing the type of listener.
可以通过在选择元素上调用.on(event, function)
并传递侦听器的类型来附加.on(event, function)
。
Lets start with the most basic interactive functionalities.
让我们从最基本的交互功能开始。
In the above example, click on js tab. See what are all the event handlers attached on the circles. Reload page and open console by pressing F12 and click on “Run Pen”.circles.on(‘mouseover’, console.log)
this console logs all the parameters passed to callback functions. circles.on(‘mouseover’, (event, data)=> {})
1st Event details, 2nd bond Data. This event
is used is get the current event details which can used for variety of things like drag and drop and zoom. Alternatively, you can directly access event
in js like this circles.on(‘click’, () => console.log(“Event”, event))
circles.on(‘dblclick’, ondblClick)
: On double click event, here in the example we passed a function which turns the element “red”.circles.on(‘wheel’, (d, i, n) => console.log(“weeeee”, i))
: On scroll event, which is very handy for user friendly zooming event and last example ondrag
event which is bit different where we have to call d3.drag()
function on the element. Which has its on events like start
, drag
, end
.
在上面的示例中,单击js选项卡。 查看圆上附加的所有事件处理程序。 重新加载页面并按F12打开控制台,然后单击“运行笔”。 circles.on('mouseover', console.log)
此控制台记录传递给回调函数的所有参数。 circles.on('mouseover', (event, data)=> {})
第一事件详细信息,第二债券数据。 使用此event
是获取当前事件的详细信息,该事件的详细信息可用于拖放和缩放之类的各种操作。 另外,您也可以直接在js中访问event
,例如circles.on('click', () => console.log(“Event”, event))
circles.on('dblclick', ondblClick)
:发生双击事件时,在此示例中,我们传递了一个将元素变为“红色”的函数。 circles.on('wheel', (d, i, n) => console.log(“weeeee”, i))
:滚动事件,对于用户友好的缩放事件和最后一个示例ondrag
事件非常方便不同之处在于我们必须在元素上调用d3.drag()
函数。 它具有on事件,例如start
, drag
, end
。
circles.call(d3.drag()
.on(“start”, console.log)
.on(“drag”, onDrag)
.on(“end”, console.log))
In onDrag
function we select the element and change its cx
property with x
property from its event
.
在onDrag
函数中,我们选择元素并从其event
x
属性更改其cx
属性。
function onDrag(d,i,n) {
d3.select(this).attr(“cx”, event.x)
}
Remember only traditional function
passes context in this
while arrow function refers to its relative parent context. If its an arrow function it should look like.
请记住,只有传统function
会在this
传递上下文,而箭头函数是指其相对父上下文。 如果它具有箭头功能,则应该看起来像。
const onDrag = (d,i,n) => {
d3.select(n[i]).attr(“cx”, event.x)
}
Here is the list of most used mouse events.
这是最常