这个想法是让一个对象对该对象附近的鼠标移动使用react。
这就是我目前在这方面的进展:
//declaring a canvas
var canvas = d3.select("body")
.append("svg")
.attr("width", 100)
.attr("height", 100);
//create circle with attributes and listeners
var circles = canvas.selectAll("circle")
.data([1])
.enter()
.append("circle")
.attr("cy", 50).attr("cx", 50).attr("r", 20)
.style({"fill": "grey"})
.on("mousemove", handleMouseMove);
//listener on mouse move inside the canvas
function handleMouseMove(){
var coordinates = [0, 0];
coordinates = d3.mouse(this);
var x = coordinates[0];
var y = coordinates[1];
console.log(x,y);
console.log(this.attributes);
}
只有将鼠标悬停在对象上时,我才能获取该对象及其属性 - 请参阅最后一个 console.log();
。我被困住了。请分享您对解决方案的想法(如果有)。
最佳答案
如果可以的话,也许最干净的方法是在现有的圆圈下方放置另一个半径更大的圆圈并填充透明:
var g = canvas.selectAll("g")
.data([1])
.enter()
.append("g")
.on("mouseover", handleMouseOver) // event handlers here are applied
.on("mouseout", handleMouseOut) // to both 'circle'
g.append('circle').classed('invisible', true) // this goes before the
.attr("cy", 50) // visible circle
.attr("cx", 50)
.attr("r", 40)
.style({"fill": "transparent"});
g.append('circle').classed('visible', true)
.attr("cy", 50)
.attr("cx", 50)
.attr("r", 20)
.style({"fill": "grey"});
function handleMouseOver(d,i){
d3.select(this).select('.visible').transition()
.style({"fill": "red"});
};
function handleMouseOut(d,i){
d3.select(this).select('.visible').transition()
.style({"fill": "green"});
};
或者如果您想使用鼠标位置:
var circles = canvas.selectAll("circle")
.data([1])
.enter()
.append("circle")
.attr("cy", 50)
.attr("cx", 50)
.attr("r", 20)
.style({"fill": "grey"})
.on("mousemove", handleMouseMove);
function handleMouseMove(){
var coordinates = [];
coordinates = d3.mouse(this);
var x = coordinates[0];
var y = coordinates[1];
if (x>10 && x<90 && y>10 && y<90) { // example values; this is a rectangle but you can use more complex shapes
d3.select('.visible').style({"fill": "red"});
}
else {
d3.select('.visible').style({"fill": "green"});
}
这是FIDDLE您可以在其中看到两个版本。
希望对您有帮助...
关于javascript - 如何使 D3js 对象在鼠标移动到对象附近时更改其属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40534414/