Created
July 31, 2014 09:42
-
-
Save jakosz/d1fe172445cd753b7d5c to your computer and use it in GitHub Desktop.
Draw a straight line using mouse
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> | |
<meta charset='utf-8'> | |
<style> | |
body { | |
background: rgb(200,200,200); | |
} | |
svg { | |
margin: auto; | |
display: block; | |
background: white; | |
} | |
</style> | |
<body> | |
<script src="http://d3js.org/d3.v3.min.js"></script> | |
<script src="draw-a-line.js"></script> | |
<script> | |
var mainw = 960, | |
mainh = 500; | |
d3.select('body').append('svg') | |
.attr('width', mainw) | |
.attr('height', mainh); | |
function draw(selection){ | |
var xy0, | |
path, | |
keep = false, | |
line = d3.svg.line() | |
.x(function(d){ return d[0]; }) | |
.y(function(d){ return d[1]; }); | |
selection | |
.on('mousedown', function(){ | |
keep = true; | |
xy0 = d3.mouse(this); | |
path = d3.select('svg') | |
.append('path') | |
.attr('d', line([xy0, xy0])) | |
.style({'stroke': 'black', 'stroke-width': '1px'}); | |
}) | |
.on('mouseup', function(){ | |
keep = false; | |
}) | |
.on('mousemove', function(){ | |
if (keep) { | |
Line = line([xy0, d3.mouse(this).map(function(x){ return x - 1; })]); | |
console.log(Line); | |
path.attr('d', Line); | |
} | |
}); | |
} | |
d3.select('svg').append('rect') | |
.attr('x', 0) | |
.attr('y', 0) | |
.attr('width', mainw) | |
.attr('height', mainh) | |
.style({'fill': 'white'}) | |
.call(draw); | |
</script> | |
</body> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment