Created
August 4, 2019 08:40
-
-
Save imohitmayank/a40c78c497bf49e4c2519d7f58170f48 to your computer and use it in GitHub Desktop.
Draw bezier curve using Processing.py
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
# Libraries | |
import time | |
# Points | |
p = [{"x" : 100, "y" : 300}, {"x" : 500, "y" : 100}, {"x" : 700, "y" : 300}] | |
# default values | |
prev_x = p[0]['x'] | |
prev_y = p[0]['y'] | |
t = 0 | |
def setup(): | |
"""First called function to setup environment | |
""" | |
# size of window | |
size(900, 500) | |
# background color | |
background(255, 255, 255) | |
# function to setup bezier prerequisites | |
setup_bezier() | |
def draw(): | |
"""The main drawing function, called iteratilvely. | |
""" | |
# calling some global variables | |
global prev_x, prev_y, t | |
# setting the stroke weight for curve | |
strokeWeight(3) | |
# Slow down the processing - otherwise it will be over in a jiffy !! | |
time.sleep(0.01) | |
# stroke color - a splash of reddish | |
stroke(190, 0, 0) | |
# find the next bt | |
next_x, next_y = find_next_bt(t) | |
# draw line of curve | |
line(prev_x, prev_y, next_x, next_y) | |
# replace prev with next | |
prev_x = next_x | |
prev_y = next_y | |
# increment the t | |
t += 0.01 | |
# stopping critera | |
if t > 1.01: | |
# stop calls to draw() | |
noLoop() | |
def drawPoint(i, textOffset = 10): | |
# set the stroke | |
stroke(0) | |
# set the weight of stroke | |
strokeWeight(7) | |
# draw point | |
point(p[i]['x'], p[i]['y']) | |
# fill point with black color | |
fill(0) | |
# draw text - string and point of placement | |
text("P{0}".format(i), p[i]['x'] + textOffset, p[i]['y'] + textOffset) | |
def setup_bezier(): | |
"""Creates anchor & control points and draws lines between them | |
""" | |
# Step 1: Draw the achor and control points | |
for i in range(3): | |
drawPoint(i) | |
# Step 2: Draw the lines between the control and anchor points | |
# stroke color | |
stroke(150) | |
# width of stroke | |
strokeWeight(1) | |
# draw line between p0 and p1 | |
line(p[0]['x'], p[0]['y'], p[1]['x'], p[1]['y']) | |
# draw line between p1 and p2 | |
line(p[1]['x'], p[1]['y'], p[2]['x'], p[2]['y']) | |
def find_next_bt(t): | |
"""Computes the next iteration point of quadratic bezier curve | |
""" | |
# calulate the x-axis | |
x = (1 - t) * (1 - t) * p[0]['x'] + 2 * (1 - t) * t * p[1]['x'] + t * t * p[2]['x']; | |
# calulate the y-axis | |
y = (1 - t) * (1 - t) * p[0]['y'] + 2 * (1 - t) * t * p[1]['y'] + t * t * p[2]['y']; | |
# return | |
return x, y |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment