This is a drag demo which can avoid noticeable jump while dragging.
Last active
October 25, 2017 07:59
-
-
Save 1Cr18Ni9/b70bb5e57e23197803932f5ffc5ceeed to your computer and use it in GitHub Desktop.
About Drag and its Origin Position
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
license: mit |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<head> | |
<meta charset="utf-8"> | |
<script src="https://d3js.org/d3.v3.min.js"></script> | |
<style> | |
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; } | |
svg { border: 1px dashed #ccc; } | |
</style> | |
</head> | |
<body> | |
<div id="container"></div> | |
<script> | |
"use strict"; | |
var data = [ | |
{x: 10, y: 10}, | |
{x: 60, y: 60}, | |
{x: 80, y: 20}, | |
] | |
var generator = d3.svg.line() | |
.x(function(d){return d.x}) | |
.y(function(d){return d.y}); | |
var svg = d3.select('#container') | |
.append('svg') | |
.attr({ | |
width: 500, | |
height: 300 | |
}); | |
function onDrag(d){ | |
var x = d3.event.x, | |
y = d3.event.y; | |
if((x >= 0 && x <= 500) && (y >= 0 && y <= 300)){ | |
d3.select(this) | |
.attr('transform', 'translate(' + [x, y] + ')') | |
} | |
} | |
var drag = d3.behavior.drag() | |
.origin(getOrigin) | |
.on('drag', onDrag); | |
svg.append('path') | |
.datum(data) | |
.attr({ | |
fill : '#000', | |
stroke : '#ccc', | |
"stroke-width": 5, | |
d : generator | |
}) | |
.call(drag); | |
// first time of drag the transform attribute will be null | |
// so I set p originally to [x:0, y:0] and return it. | |
// After that drag, every time of drag I use regx to extract | |
// the translate point then return it. | |
function getOrigin(){ | |
var p = {x: 0, y: 0}, self = d3.select(this); | |
if(self.attr('transform')){ | |
var str = self.attr('transform'), point; | |
point = str.match(/translate\((-?[\d.]+)[, ]+(-?[\d.]+)\)/) | |
.slice(1, 3); | |
p = {x: +point[0], y: +point[1]}; | |
} | |
return p; | |
} | |
/* | |
Alternaltive way: using d3.transform | |
function getOrigin(){ | |
var p = d3.transform(d3.select(this).attr("transform")) | |
.translate; | |
return { x: p[0], y: p[1] }; | |
} | |
*/ | |
</script> | |
</body> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment