Instantly share code, notes, and snippets.

Last active September 11, 2015 23:49
Show Gist options
• Save enjalot/f8c41743ca81d7828c3a to your computer and use it in GitHub Desktop.
visfest experiment #3
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

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
 var Sampler = function() {} Sampler.getSamples = function(path, num) { var len = path.getTotalLength() var p, t; var result = [] for(var i = 0; i < num; i++) { p = path.getPointAtLength(i * len/num); t = Sampler.getTangent(path, i/num * 100); result.push({ x: p.x, y: p.y, point: p, tangent: t, perp: Sampler.rotate2d(t.v, 90) }); } return result } Sampler.getTangent = function(path, percent) { // returns a normalized vector that describes the tangent // at the point that is found at *percent* of the path's length var fraction = percent/100; if(fraction < 0) fraction = 0; if(fraction > 0.99) fraction = 1; var len = path.getTotalLength(); var point1 = path.getPointAtLength(fraction * len - 0.1); var point2 = path.getPointAtLength(fraction * len + 0.1); var vector = { x: point2.x - point1.x, y: point2.y - point1.y } var magnitude = Math.sqrt(vector.x*vector.x + vector.y*vector.y); vector.x /= magnitude; vector.y /= magnitude; return {p: point1, v: vector }; } Sampler.rotate2d = function(vector, angle) { //rotate a vector angle *= Math.PI/180; //convert to radians return { x: vector.x * Math.cos(angle) - vector.y * Math.sin(angle), y: vector.x * Math.sin(angle) + vector.y * Math.cos(angle) } }