Skip to content

Instantly share code, notes, and snippets.

@techird
Last active December 26, 2015 21:09
Show Gist options
  • Save techird/7214206 to your computer and use it in GitHub Desktop.
Save techird/7214206 to your computer and use it in GitHub Desktop.
var ns = 'http://www.w3.org/2000/svg',
svg = document.createElementNS(ns, 'svg'),
div = document.createElement('div');
document.body.appendChild(div);
div.appendChild(svg);
svg.setAttribute('width', 400);
svg.setAttribute('height', 300);
svg.style.background = '#eee';
function vectorAdd(v1, v2) {
return [v1[0] + v2[0], v1[1] + v2[1]];
}
function vectorMinus(v1, v2) {
return vectorAdd(v1, vectorMulti(v2, -1));
}
function vectorMulti(v, f) {
return [v[0] * f, v[1] * f];
}
function getCurveData(points) {
var last, current, next, ctl, dir;
var data;
last = points.shift();
current = points.shift();
next = points.shift();
data = 'M' + last.join(' ') + ' S';
var parts = [];
while(true) {
dir = vectorMinus(next, last);
dir = vectorMulti(dir, 0.2);
ctl = vectorMinus(current, dir);
data += [ctl.join(' '), current.join(' ')].join(' ') + ' ';
if(current == next) break;
last = current;
current = next;
next = points.shift() || current;
}
return data + 'z';
}
var line = document.createElementNS(ns, 'path');
line.setAttribute('fill', 'none');
line.setAttribute('stroke', 'red');
svg.appendChild(line);
var points = [
[10, 100],
[210, 110],
[210, 210],
[10, 100]
];
var data = getCurveData(points);
console.log(data);
line.setAttribute('d', data);
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
</body>
<script src="all.js"></script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment