JS

Nambafa

Graphics tutorials


Downloads: tut_02.zip

[ Nambafa's pixel graphics tutorial : Part 2 ]

Overview

This part of the tutorial will cover rectangles and ellipses (in their simples form). In order to make them a bit more interesting to look at, we will let them bounce around on the display. The main sections of the presentation will thus be:

  • pixel shapes
  • rectangles
  • ellipses
  • bouncing objects

Added buffer components: imp, g2d, fill

The first thing we will do is to extend the buffer class with some new components:

 
class MyBuffer extends MyBuffer_basic {  
 
  properties: 
    imp
    g2d
    fill
  
  methods:
    constructor(width,height)
    
}

These properties are objects that will hold different sets of tasks related to the buffer. Defining such components is a convenient way to structure the code into functional blocks: imp will be used (later) for importing external data into the buffer, g2d for basic 2D graphics and fill for filling the buffer with gradients etc.

In this part of the tutorial we will use a couple of functions from g2d to draw rectangles and ellipses, and a function from fill to create a gradient background.

However, since rectangles and ellipses are two types of pixel data, or pixel shapes, we will rather implement the core functionality in a more general class called MyPixelShape that will handle pixel shapes in general.

Pixel shapes

Pixel shapes are simply collections of pixel data that have a center location and connected pixels that are defined relative to the center

extensions to the putpixel -> putshape (2D)

already saw some examples in the previous part (s,+)

 
class MyPixelShape {  
 
  properties: 
    x
    y
    rgbx
    length    
  
  methods:
    constructor(x,y,opt)
    put(buffer,x,y)
    rotate(da)
    unrotate()
    unrotata()
    fix()
    scale(sx,sy)
    flip_x()
    flip_y()
    set_w(w)
    set_h(h)
    [add(s)]
    [cut(s)]
    color(val,type)
    static verify_rgbx_fixed (rgbx)
    static new_rect     (hw,hh,rgbx=[0,0,0],spp=2)
    static new_ellipse  (rx,ry,rgbx=[0,0,0],spp=2)
    
}

Rectangles

Ellipses

Bouncing objects

Simple idea: let the objects move in a given direction until it "hits" the edge of the screen, where it should reflect back

Basically each object needs to keep track of its position as it moves along and compare it to the limits of the screen buffer to detect when it hits and needs to update its parameters (direction of movement etc.)

In order to make it more interesting, I have a added some pulasting behaviour to the shapes when they hit the edge (but it makes the code a bit more comprehensive, so I am not sure if it was a good idea or not)

Demo

Here comes the demo of today's applet - just press start to check it out! :)

...

Downloads: tut_02.zip