Last active
December 20, 2018 15:42
-
-
Save nataliefreed/89da12ee81c2846ce4bdb4027f58696c to your computer and use it in GitHub Desktop.
curveBetween example in P5.js: function that draws symmetrical bezier curves between two points
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
/* | |
CurveBetween function by Natalie Freed, 9/22/16 | |
Draws symmetrical bezier curves between two points, | |
includes example of use | |
*/ | |
function setup() { | |
createCanvas(600, 600); | |
/* | |
inputs to curveBetween: | |
x1, y1, x2, y2: coordinates of start and end points | |
d: how wide curve is as percentage of distance between start and end points | |
h: how high curve is as percentage of distance between start and end points | |
flip: whether curve should be flipped up or down (0 or 1) ie. smile or frown! | |
*/ | |
// examples | |
noFill(); | |
stroke(255, 0, 0); //red | |
ellipse(100, 50, 10, 10); | |
ellipse(400, 300, 10, 10); | |
line(100, 50, 400, 300); | |
strokeWeight(2); | |
curveBetween(100, 50, 400, 300, 0.3, 0.2, 1); | |
stroke(0, 255, 0); //green | |
curveBetween(10, 10, 200, 400, 0.5, 0.7, 1); | |
stroke(0, 0, 255); //blue | |
curveBetween(10, 300, 400, 50, 0.3, 0.2, 0); | |
stroke(255, 0, 255); //pink | |
push(); | |
for(var i=0;i<10;i++) { | |
curveBetween(10, 450, 50, 450, 0.2, 0.5, 1); | |
translate(40, 0); | |
} | |
pop(); | |
stroke(0, 255, 255); //cyan | |
push(); | |
for(var i=0;i<10;i++) { | |
curveBetween(10, 550, 10+20*i, 550, 0.2, 0.5, 1); | |
translate(20*i, 0); | |
} | |
pop(); | |
} | |
function draw() { | |
} | |
function curveBetween(x1, y1, x2, y2, d, h, flip) { | |
//find two control points off this line | |
var original = p5.Vector.sub(createVector(x2, y2), createVector(x1, y1)); | |
var inline = original.copy().normalize().mult(original.mag() * d); | |
var rotated = inline.copy().rotate(radians(90)+flip*radians(180)).normalize().mult(original.mag() * h); | |
var p1 = p5.Vector.add(p5.Vector.add(inline, rotated), createVector(x1, y1)); | |
//line(x1, y1, p1.x, p1.y); //show control line | |
rotated.mult(-1); | |
var p2 = p5.Vector.add(p5.Vector.add(inline, rotated).mult(-1), createVector(x2, y2)); | |
//line(x2, y2, p2.x, p2.y); //show control line | |
bezier(x1, y1, p1.x, p1.y, p2.x, p2.y, x2, y2) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment