Instantly share code, notes, and snippets.

# albertsun/circle-segment.js

Created January 29, 2015 18:18
Show Gist options
• Save albertsun/90339d1b64cd9b4ae203 to your computer and use it in GitHub Desktop.
Drawing partial circles with area proportional to a value (good!) or angle proportional to a value (misleading!)
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
 (function() { var circleSegment = {}; var degreesToRadians = function(deg) { return deg*Math.PI*2/360; }; // takes an angle in radians // returns 0-1 the proportion of a circle's area // that a segment bounded by arc of that angle fills // (allowing segment to range in size to the full circle) var angleToProportion = function(radians) { return (radians-Math.sin(radians))/(2*Math.PI); }; var calc_table = []; for (var i=1;i<=360;i++) { calc_table.push(angleToProportion(degreesToRadians(i))); } // takes a 0-1 proportion of area // returns the angle of arc in radians that defines a circle segment // filling that proportion of the circle // accurate to within 1/360th of a circle (1°) var proportionToAngle = function(proportion) { proportion = proportion % (2*Math.PI); var curr = calc_table[0]; for (var i=0;i<360;i++) { if (calc_table[i] > proportion) { return degreesToRadians(Math.abs( calc_table[i-1]-proportion ) < Math.abs( calc_table[i]-proportion ) ? i : i+1); } } return degreesToRadians(calc_table.length); }; circleSegment.angleToProportion = angleToProportion; circleSegment.proportionToAngle = proportionToAngle; if (typeof define === 'function' && define.amd) { define([], function() { return circleSegment; }); } else { this.circleSegment = circleSegment; } }).call(this);
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