当用户按下并按住鼠标按键时,我正在尝试实现某种可视化。就像在第一人称射击游戏中,你有一个自动武器,你可以按住鼠标键,它仍然可以射击。在本例中,我将使用d3在画布上生成比方说圆。因此,如果用户点击并按住画布,一堆圆圈将被添加到DOM中,并将继续添加,直到他们松开为止。目前,这是我已经尝试过的:
var drag = d3.behavior.drag()
.on('dragstart', function () {
d3.event.sourceEvent.stopPropagation();
d3.event.sourceEvent.preventDefault(); })
.on('drag', function (d) {
console.log('dragging')
});这工作得很好,我在控制台中看到了一堆“拖动”,但由于我需要调用一个与类关联的函数,所以我在传递正确的This上下文时遇到了麻烦,这样我就可以调用该函数。我总是得到错误‘找不到属性'X’的未定义‘,这是非常有意义的。如何/可以将上下文传递给d3拖动行为?
这有点可笑,因为我寻找的大多数帖子都是关于删除多个点击或多个点击被触发的。
发布于 2015-03-15 08:08:03
你可以在mousedown事件中使用setInterval来做到这一点,在mouseup中你可以删除间隔。
请看一下这个演示jsFiddle。它就是这个添加了点击行为的demo。
代码可以改进,因为我认为它在每次单击时都会重新创建节点映射,最好是将新节点添加到数据中,而只将新节点添加到force布局中。
var width = 500,
height = 300;
var newNode = function() {
return {
radius: Math.random() * 12 + 4
};
},
nodes = d3.range(20).map(newNode),
root = nodes[0],
color = d3.scale.category10();
root.radius = 0;
root.fixed = true;
var force = d3.layout.force()
.gravity(0.05)
.charge(function(d, i) {
return i ? 0 : -2000;
})
.nodes(nodes)
.size([width, height]);
force.start();
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
var update = function() {
svg.selectAll("circle")
.data(nodes) //.slice(1))
.enter().append("circle")
.attr("r", function(d) {
return d.radius;
})
.style("fill", function(d, i) {
return color(i % 3);
});
};
update();
force.on("tick", function(e) {
var q = d3.geom.quadtree(nodes),
i = 0,
n = nodes.length;
while (++i < n) q.visit(collide(nodes[i]));
svg.selectAll("circle")
.attr("cx", function(d) {
return d.x;
})
.attr("cy", function(d) {
return d.y;
});
});
var intervalId = null,
pos = null;
var addNewNode = function() {
var nextNode = newNode();
nextNode.x = pos[0];
nextNode.y = pos[1];
nodes.push(nextNode);
d3.select('#debug').text('pos x=' + pos[0] + ',y=' + pos[1] + '-nodes=' + nodes.length);
update();
force.start();
};
svg.on('mousedown', function() {
//console.log('down');
//addNewNode(this);
pos = d3.mouse(this);
intervalId = setInterval(addNewNode, 100);
})
.on('mouseup', function() {
//console.log('up');
clearInterval(intervalId);
})
.on("mousemove", function() {
pos = d3.mouse(this);
root.px = pos[0];
root.py = pos[1];
force.resume();
})
.on("mouseleave", function() {
if (intervalId) clearInterval(intervalId);
});
function collide(node) {
var r = node.radius + 16,
nx1 = node.x - r,
nx2 = node.x + r,
ny1 = node.y - r,
ny2 = node.y + r;
return function(quad, x1, y1, x2, y2) {
if (quad.point && (quad.point !== node)) {
var x = node.x - quad.point.x,
y = node.y - quad.point.y,
l = Math.sqrt(x * x + y * y),
r = node.radius + quad.point.radius;
if (l < r) {
l = (l - r) / l * .5;
node.x -= x *= l;
node.y -= y *= l;
quad.point.x += x;
quad.point.y += y;
}
}
return x1 > nx2 || x2 < nx1 || y1 > ny2 || y2 < ny1;
};
}<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<div id="debug"></div>
https://stackoverflow.com/questions/29054677
复制相似问题