Skip to content

Instantly share code, notes, and snippets.

@amundo
Created September 26, 2015 20:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amundo/3ef706c5b595a07bfa07 to your computer and use it in GitHub Desktop.
Save amundo/3ef706c5b595a07bfa07 to your computer and use it in GitHub Desktop.
path from numbers in d3

Playing with lines

Type two integers per line in the text area, and a line will be drawn on the right.

<!doctype html>
<html>
<head>
<title>
learning d3 lines
</title>
<meta charset=utf-8>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<style>
svg {
background: #333;
float:right;
}
path {
stroke: #eee;
stroke-width: 2px ;
fill: red;
}
textarea {
height: 20em;
}
</style>
</head>
<body>
<svg></svg>
<textarea placeholder="Type two integers per line here to see a path drawn to the right"></textarea>
<p id=pathData></p>
<script>
var
width = '500px',
height = '300px';
var readLineData = () => {
var
text = document.body.querySelector('textarea').value.trim(),
lines = text.split(/\n/g).filter(line => line);
var pairs = lines.map(line => line.trim().split(/[ ]+/g));
return pairs.map(pair => {
return { x: parseInt(pair[0]), y: parseInt(pair[1]) }
})
}
var svg = d3.select('svg'),
lineFunction,
lineGraph;
svg.attr({ width : width, height : height });
var pathData = document.body.querySelector('#pathData');
function renderD(){
pathData.textContent = document.body.querySelector('path').getAttribute('d');
}
function draw(){
d3.selectAll('path').remove();
lineFunction = d3.svg.line()
.x(function(d) { return d.x; })
.y(function(d) { return d.y; })
.interpolate("linear");
lineGraph = svg.append("path")
.attr("d", lineFunction(readLineData()))
}
document.addEventListener('DOMContentLoaded', draw);
var ta = document.querySelector('textarea')
ta.addEventListener('input', draw);
ta.addEventListener('input', renderD);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment