Drawing Hair

July 2, 2008 | drawing

Applying the "hair" method to a Rope object will render organic flowing threads to the canvas.

#!/usr/local/bin/macruby

framework 'cocoa'
require 'rubygems'
require 'hotcocoa/graphics'
include HotCocoa
include Graphics

# create a new 400x400 pixel canvas to draw on
canvas = Canvas.new :type => :image, :filename => 'hair.png', :size => [400,400]

# choose a random color and set the background to a darker variant
clr = Color.random.a(0.5)
canvas.background(clr.copy.darken(0.6))

# create a new rope with 200 fibers
rope = Rope.new(canvas)
rope.width = 100
rope.fibers = 200
rope.strokewidth = 0.4
rope.roundness = 3.0

# randomly rotate the canvas from its center
canvas.translate(canvas.width/2,canvas.height/2)
canvas.rotate(random(0,360))
canvas.translate(-canvas.width/2,-canvas.height/2)

# draw 50 ropes
ropes = 50
for i in 0..ropes do
    canvas.stroke(clr.copy.analog(20, 0.8))   # rotate hue up to 20 deg left/right, vary brightness/saturation by up to 70%
    rope.x0 = -100                            # start rope off bottom left of canvas
    rope.y0 = -100
    rope.x1 = canvas.width + 100              # end rope off top right of canvas
    rope.y1 = canvas.height + 100
    rope.hair                                 # draw rope in organic "hair" style
end

# save the canvas
canvas.save