Last active
September 13, 2017 14:47
-
-
Save tom2strobl/14a77f3cfc4f3b7650636d46cacd52e3 to your computer and use it in GitHub Desktop.
draw an arc of a circle with plain math and a react render
This file contains hidden or 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 polarToCartesian(centerX, centerY, radius, angleInDegrees) { | |
var angleInRadians = (angleInDegrees-90) * Math.PI / 180.0; | |
return { | |
x: centerX + (radius * Math.cos(angleInRadians)), | |
y: centerY + (radius * Math.sin(angleInRadians)) | |
}; | |
} | |
function describeArc(x, y, radius, startAngle, endAngle){ | |
var start = polarToCartesian(x, y, radius, endAngle); | |
var end = polarToCartesian(x, y, radius, startAngle); | |
var largeArcFlag = endAngle - startAngle <= 180 ? "0" : "1"; | |
var d = [ | |
"M", start.x, start.y, | |
"A", radius, radius, 0, largeArcFlag, 0, end.x, end.y | |
].join(" "); | |
return d; | |
} | |
function paintCircle(diameter, progress) { | |
const endAngle = 360 * (progress / 100); | |
return describeArc(diameter/2, diameter/2, (diameter/2) - 2, 0, endAngle - 0.0001); // cutting off a super tiny piece because 360 would actually not be rendered | |
} | |
// lets say state.progress is 70, you can animate it as well with react-motion | |
render() { | |
<svg width="36" height="36"> | |
<path fill="none" stroke="#000000" strokeWidth="2" strokeLinecap="round" d={paintCircle(36, this.state.progress)} /> | |
</svg> | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment