Drawing With Algorithms

Image created

Algorithm

In this example, we first set up two functions, dist() and colorize(). The dist() function compares the distance from the current pixel to a set x and y coordinate and returns a value based on the comparison, this is used in the colorize function to 'fade' the a color value based on a pixel's distance from a fixed point. The colorize() function takes a pixel as an argument and uses the position of the pixel in relation to three different fixed points, via the dist() function to assign unique RGB values.

The next part of the program initializes the new image and operates a for loop to check each pixel. Each pixel is tested against one of five if statements each of which call the colorize() function on the pixel if the statement is true. The first if statement draws the X from corner to corner, each subsequent if statement fills one of the four quadrants formed by the X.

Code

function dist(pixel, x,y) {
     var dx = pixel.getX() - x;
     var dy = pixel.getY() - y;
     return Math.sqrt(dx * dx + dy *dy);
}
 
function colorize(pixel){
    if (dist(pixel, output.width/2,0) < 400){
        pixel.setRed(300-dist(pixel,output.width/2,0));
    }

    if (dist(pixel, output.width-1, output.height-1) < 400){
        pixel.setGreen(300 - dist(pixel, output.width-1, output.height-1));
    }

    if (dist(pixel, 0, output.height-1) < 400){
        pixel.setBlue(300 - dist(pixel, 0, output.height-1));
    }
}
 
var output = new SimpleImage(320,320);

for (var pixel of output.values()) {
    x = pixel.getX();
    y = pixel.getY();
    w = output.width-1
    h = output.height-1
    
    if (y === x || x+y === w) {
        colorize(pixel);
    }
    
    if ( x+y < w-10 && x < y-10 && x%4 === 0 ) {
        colorize(pixel);
    }
    
    if ( x+y < w-10 && y < x-10 && (x-y)%6 === 0 ) {
        colorize(pixel);
    }
    
    if ( x+y > w+9 && y < x-10 && ((x-y)%6 === 0 || (x+y)%6 === 0) ) {
        colorize(pixel);
    }
    
    if ( x+y > w+9 && x < y-10 && (x%4 === 0 || (x+y)%6 === 0 )) {
        colorize(pixel);
    }
}

print(output);
    

2015, Paul Ward