Last active
December 30, 2015 05:38
-
-
Save justjake/7783517 to your computer and use it in GitHub Desktop.
Line drawing demo. Use with Coffeescript mode in Processing 2
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
setup: -> | |
# Processing.js setup | |
size(1600, 900) | |
noLoop() | |
class Point | |
constructor: (@x, @y) -> | |
sub: (other) -> | |
new Point(@x - other.x, @y - other.y) | |
magnitude: -> | |
@x*@x + @y*@y | |
# line made of two points | |
class Line | |
constructor: (@start, @end) -> | |
draw: -> | |
# stroke must be done after | |
line(@start.x, @start.y, @end.x, @end.y) | |
# stateful storage | |
@points = [] # current line | |
@all = [] # all points ever drawn | |
# aliases | |
@p = (x, y) -> new Point(x, y) | |
@l = (s, e) -> new Line(s, e) | |
draw_lines: (arr_of_line) -> | |
for l in arr_of_line | |
l.draw() | |
# detect points that are close together | |
# draw the return value with @draw_lines | |
detect_close: (pts, cur) -> | |
close = [] | |
for p in pts | |
dx = p.x - cur.x | |
dy = p.y - cur.y | |
d = dx*dx + dy*dy | |
if d < 3000 and d > 250 | |
close.push @l(p, cur) | |
return close | |
# run on redraw() called | |
draw: -> | |
len = @points.length | |
cur = @points[len-1] | |
prev = @points[len-2] | |
# detect points close to the current one, and draw a line between them and the current point. | |
# very very cool looking | |
@draw_lines @detect_close(@all, cur) | |
stroke(50) | |
# link to 5 points ago. pretty cool looking | |
line(@points[len - 6].x, @points[len - 6].y, cur.x, cur.y) if @points[len - 6]? | |
stroke(20) | |
# draw basic line. not super cool | |
if prev? | |
line(prev.x, prev.y, cur.x, cur.y) | |
stroke(0) | |
mouseDragged: -> | |
# add new point if the mouse hase moved | |
cur = @p(mouseX, mouseY) | |
@points.push cur | |
@all.push cur | |
console.log("added point", cur) | |
redraw(); | |
mousePressed: -> | |
# start a new line | |
@points = [] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
SO #GOOD