Last active
April 20, 2021 18:23
-
-
Save chiunhau/25b318ab453468c4073dc0de72a5408a to your computer and use it in GitHub Desktop.
Draw ellipse with bezierVertex() in p5.js
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
/* | |
* @param {Number} x x-coordinate for the ellipse | |
* @param {Number} y y-coordinate for the ellipse | |
* @param {Number} r radius of the ellipse | |
* @param {Number} n segements of the ellipse, defaults to 4 | |
*/ | |
p5.prototype.bezierEllipse(x, y, r, n) { | |
// caulate length of each controls: r - (4/3)*tan(PI/(2n)) | |
var ctrl = r * (4 / 3) * tan(PI / (2 * n)); | |
// translate to the center of circle: (x, y) | |
push(); | |
translate(x, y); | |
beginShape(); | |
vertex(r, 0); | |
for(var i = 0; i < n; i ++) { | |
var firstAngle = (PI * 2 / n) * i; | |
var secondAngle = (PI * 2 / n) * (i + 1); | |
var firstVtx = {x: cos(firstAngle) * r, y: -sin(firstAngle) * r}; | |
var secondVtx = {x: cos(secondAngle) * r, y: -sin(secondAngle) * r}; | |
var firstCtrl = {x: firstVtx.x - ctrl * sin(firstAngle), y: firstVtx.y - ctrl * cos(firstAngle)}; | |
var secondCtrl = {x: secondVtx.x + ctrl * sin(secondAngle), y: secondVtx.y + ctrl * cos(secondAngle)}; | |
drawBezierV(firstCtrl.x, firstCtrl.y, secondCtrl.x,secondCtrl.y, secondVtx.x, secondVtx.y); | |
} | |
noFill(); | |
endShape(); | |
pop(); | |
} | |
// extends the original bezierVertex(), for visualize and debig purpose | |
function drawBezierV(x1, y1, x2, y2, x3, y3) { | |
bezierVertex(x1, y1, x2, y2, x3, y3); | |
fill('#4aff2e'); //marks two control point with light green | |
ellipse(x1, y1, 5, 5); | |
ellipse(x2, y2, 5, 5); | |
fill('#ff2e2e'); // red | |
rectMode(CENTER); //marks anchor point with red | |
rect(x3, y3, 8, 8); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment