1. NodeBox 1
    1. Homepage
    2. NodeBox 3Node-based app for generative design and data visualization
    3. NodeBox OpenGLHardware-accelerated cross-platform graphics library
    4. NodeBox 1Generate 2D visuals using Python code (Mac OS X only)
  2. Gallery
  3. Documentation
  4. Forum
  5. Blog

Canvas sorting

Posted by Frederik on Oct 02, 2007



In the new NodeBox 1.9.1 release, you can access all the graphic objects ("grobs") on the canvas. This gives some nice, new possibilities, like sorting them according to their size, color, or, as in this case, their vertical position.

# This example shows one of the possibilities of the canvas: the ability to access
# all existing objects on it.
 
size(550, 300)
 
fill(1, 0.8)
strokewidth(1.5)
 
# First, generate some rectangles, all over the canvas and randomly rotated.
for i in range(3000):
    grob = rect(random(WIDTH)-25, random(HEIGHT)-25,50, 50)
    grob.rotate(random(360))
 
# Now comes the smart part: 
# We want to sort the objects on the canvas using a custom sorting
# method; in this case, their vertical position.
# The bounds property returns the following: ( (x, y), (width, height) )
# The lambda function thus compares the y positions against eachother.
sorted_grobs = list(canvas)
sorted_grobs.sort(lambda v1, v2: v1.bounds[0][1].__cmp__(v2.bounds[0][1]))
 
# Now that we have all the graphic objects ("grobs") sorted,
# traverse them in order and change their properties.
 
# t is a counter going from 0.0 to 1.0
t = 0.0
# d is the delta amount added each step
d = 1.0 / len(sorted_grobs)
 
for grob in sorted_grobs:
    # Grobs will get bigger
    grob.scale(t)
    # Grobs's stroke will get darker
    grob.stroke = (0.6 - t, 0.50)
    t += d
 
# This is really a hack, but you can replace the internal
# grob list of the canvas with your own to change the Z-ordering.
canvas._grobs = sorted_grobs


 
Posted by nex on Oct 03, 2007

The example here is a bit nonsensical, as it would have been just as easy to achieve the same result with earlier NodeBox versions, but it still looks like a great feature, I'm sure I'll soon run into a situation where it'll come in very handy. Many thanks!

(Sorry if this comment shows up multiple times, this time I'm erring on the side of caution here ... the forum software seems to be a bit wonky ...)