Skip to content

Instantly share code, notes, and snippets.

@RobinL
Created May 11, 2013 10:34
Show Gist options
  • Save RobinL/5559579 to your computer and use it in GitHub Desktop.
Save RobinL/5559579 to your computer and use it in GitHub Desktop.
Dragging a rectangle
{"description":"Dragging a rectangle","endpoint":"","display":"svg","public":true,"require":[],"fileconfigs":{"inlet.js":{"default":true,"vim":false,"emacs":false,"fontSize":12},"_.md":{"default":true,"vim":false,"emacs":false,"fontSize":12},"config.json":{"default":true,"vim":false,"emacs":false,"fontSize":12}},"fullscreen":false,"play":true,"loop":false,"restart":true,"autoinit":true,"pause":true,"loop_type":"period","bv":false,"nclones":15,"clone_opacity":0.4,"duration":3000,"ease":"linear","dt":0.01}
//The starting location of the block
block1 = [
{ x: 0, y: 0 }
];
block2 = [
{ x: 200, y:200 }
];
//drag is a function
drag1 = d3.behavior.drag()
.origin(function(d) {
//by setting to a blank function the 'start position' of the drag is set to the
//x y coordinats of the item which has been dragged (the square)
debugger;
return d; })
.on("drag", function(d) {
//This event fires as the mouse moves, each time the position of the mouse refreshes on the screen
d.x = d3.event.x;
d.y = d3.event.y;
console.log(d.x);
redraw1();
});
drag2 = d3.behavior.drag()
.origin(function(d) {
//by setting to a blank function the 'start position' of the drag is set to the
//x y coordinats of the item which has been dragged (the square)
return d; })
.on("drag", function(d) {
//This event fires as the mouse moves, each time the position of the mouse refreshes on the screen
d.x = d3.event.x;
d.y = d3.event.y;
console.log(d.x);
redraw2();
});
svg = d3.select("svg");
g = svg.selectAll(".rect1")
.data(block1);
gEnter = g.enter().append("rect")
.attr("x", function(d) {return d.x})
.attr("y", function(d) {return d.y})
.attr("height", 100)
.attr("width", 100)
.attr("fill","#003399")
.attr("class", "rect1")
.call(drag1); //Attach the drag behaviour to the object
g = svg.selectAll(".rect2")
.data(block2);
gEnter = g.enter().append("rect")
.attr("x", function(d) {return d.x})
.attr("y", function(d) {return d.y})
.attr("height", 50)
.attr("width", 50)
.attr("class", "rect2")
.call(drag2); //Attach the drag behaviour to the object
function redraw1() {
var a =svg.selectAll(".rect1").call(drag1); //bind drag data
a.attr("x", function(d) {
return d.x})
.attr("y", function(d) {return d.y})
.call(drag1);
}
function redraw2() {
var a =svg.selectAll(".rect2").call(drag2); //bind drag data
a.attr("x", function(d) {
return d.x})
.attr("y", function(d) {return d.y})
.call(drag2);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment