path length interpolation

This commit is contained in:
Jeff Epler 2015-08-04 19:07:55 -05:00
parent 62613b53a3
commit b37cd1244d
2 changed files with 53 additions and 6 deletions

View file

@ -6,19 +6,35 @@
<script type="text/javascript" src="main.js"></script>
<style>
body { margin: 0; padding: 0; overflow:hidden; }
svg { display: block; border: 1px solid #ccc; position: absolute; top: 1%; left: 1%; width: 98%; height: 98%; background: #fff; }
svg { display: block; border: 0; position: absolute; top: 0%; left: 0%; width: 100%; height: 100%; background: #fff; }
</style>
</head>
<body height="100%">
<svg id="g" xpreserveAspectRatio="xMidYMid meet">
<svg id="s" xpreserveAspectRatio="xMidYMid meet">
<defs>
<path id="p" fill="none" stroke="blue"/>
</defs>
<g id="g"/>
<use xlink:href="#p" fill="none" stroke="blue">
</svg>
<script>
var c = new Curve(1, 1, 3, 5, 18, 18, 100);
document.getElementById("p").setAttribute("d", c.svgpath(128))
var bbox = c.bbox(256)
document.getElementById("g").setAttribute("viewBox",
fix(bbox[0]) + " " + fix(bbox[1]) + " " + fix(bbox[2] - bbox[0]) + " " + fix(bbox[3] - bbox[1]) )
var main = function () {
document.getElementById("p").setAttribute("d", c.svgpath(128))
var bbox = c.bbox(256)
bbox[0] *= 1.05
bbox[1] *= 1.05
bbox[2] *= 1.05
bbox[3] *= 1.05
document.getElementById("s").setAttribute("viewBox",
fix(bbox[0]) + " " + fix(bbox[1]) + " " + fix(bbox[2] - bbox[0]) + " " + fix(bbox[3] - bbox[1]) )
var g = document.getElementById("g")
for(var i=0; i<100; i++) {
var xy = c.xypathlen(i / 100)
g.innerHTML += "<circle cx=\"" + (xy[0].toFixed(2)) + "\" cy=\"" + (xy[1].toFixed(2)) + "\" stroke=\"black\" stroke-width=\"3\" fill=\"red\" r=\"5\"/>"
}
}
main()
</script>
</body>
</html>

31
main.js
View file

@ -91,3 +91,34 @@ Curve.prototype.tosvgdatauri = function(n, props) {
var svg = this.tosvg(n, props)
return todatauri(svg, "image/svg+xml")
}
Curve.prototype.preppathlen = function(n) {
n = n || 512
this.cl = [0];
var l = 0;
var oxy = this.xy(0)
for(var i=1; i<=n; i++) {
var phi = i * 2 * Math.PI / n;
var xy = this.xy(phi)
this.cl.push(l += Math.hypot(xy[0] - oxy[0], xy[1] - oxy[1]))
oxy = xy
}
for(var i=1; i<=n; i++) {
this.cl[i] /= l
}
this.ol = 0
this.oi = 0
}
Curve.prototype.xypathlen = function(l) {
this.cl || this.preppathlen()
if(l < this.ol) { this.oi = 0 }
this.ol = l
while(l > this.cl[this.oi]) this.oi++;
var dlen = this.cl[this.oi + 1] - this.cl[this.oi];
var dt = l - this.cl[this.oi];
var dphi = 2 * Math.PI / (this.cl.length - 1)
var phi = dphi * (this.oi + dt/dlen)
console.log(l + " " + phi + " " + this.oi + " " + dlen)
return this.xy(phi)
}