Unicorns Fart Pixels

& other internet adventures

Control & Coordinates

So GUI’s are great. Instead of having to remember complicated command line combinations and formulas, we can use a mouse to click on icons that make our computer do what we want, when we want it to.


Easy, comfortable, and uncomplicated, using visual languages to manipulate the computer is a best practice that people seem to generally agree with across the board. One industry where this has had a pretty interesting impact is graphic design. Just consider what the Adobe creative suite represents to the industry and our case for the GUI’s is made.


But while we can all admit that the 80’s and 90’s saw a jump in graphic artist’s productivity, can we really argue that there was any measurable improvement against the quality of the same work done by hand?


When the Internet happened, networked communities starting sprouting. This meant that many different people could simultaneously work on individual parts of a singular project. Hence the jump in productivity. But with file sharing and version control came a increasingly loud conversation about what it was people were using computers to make.


Now, we know that a computer can model objects, relationships, and behaviors that we recognize as being true and real. Just consider what Photoshop actually is: a graphic representation of your basic graphic tool set and all the interactions and reactions that the tools and your digital content subsequently have.


So if a computer can model what we can confirm as real, what can it do for what we can’t yet even imagine?


And that’s where code comes into play: modelling the unknown.


To understand how code is used to do this on a basic level, we have to get comfortable with the way the computer manipulates form. When it comes to placing things on the screen, there are really two main things to understand:


   1. Cartesian coordinates


   2. Raster images


>> Part 1 • Cartesian Coordinates


IRL Forms


We can use our senses to understand the forms we encounter around us, so there’s no need for us to consider the math and physics that each form presupposes in order for us to be able to manipulate them. And we can refer to IRL forms indirectly, without fear of being missunderstood.


Computer Generated Forms


However, a computer needs to know every single position of every single mark that it produces on screen. It does this by using cartesian coordinates measured against the grid of pixels that makes up your computer screen.


Porting an Image to Code


I’ve been working through the exercises on Kadenze’s “Introduction to Programming for the Visual Arts with p5.js”. Offered by the University of California, Los Angeles, Department of Arts, it teaches a creative approach to coding. What’s more, the teachers are themselves the library’s creators, so we have the opportunity to learn direct from the source (!! squee !!)


One of the first exercises involves porting an image to code and is a great example of how we can use information from the Cartesian coordinate system to create and manipulate form with code:


Select a crop of Paul Klee’s “Dream City” and draw it using p5js as a 1024 x 768 pixel program. First select an interesting/ambitious crop, then load it into a program such as Photoshop or Illustrator to read the color and coordinate data.


image

Use integer values for coordinates and only use the following functions for drawing:


line(), triangle(), quad(), rect(), ellipse(), and arc().


You must also use the stroke(), fill(), and background() functions in your sketch as well.


The idea seemed straight forward enough but proved tricky when it came to the exact placement of each graphic on the screen. The coordinate system didn’t feel as natural as I expected so plotting out the placement of each type of form using nested for loops was really helpful in figuring out how things fit and move around on the screen.


image


So here I’ve isolated and duplicated a specific part of the artwork, since I had selected a portion not quite wide enough for the 1024 x 768 dimensions given.


image


Then I outlined the shapes I could make out in the image and identified their color codes.


What’s interesting to notice here is that while the nested for loops are placing an x based on the canvas’ width and height, it’s actually also placing each x on a specific part of a coordinate system.


All shapes drawn to the screen have a position that is specified as a coordinate. All coordinates are measured as the distance from the origin in units of pixels. The origin [0, 0] is the coordinate in the upper left of the window and the coordinate in the lower right is [width-1, height-1].

- source


Kind of like if you took the top right portion of the Cartesian coordinate system (figure 1) and flipped it on it’s head (figure 2).


image

figure 1


image

figure 2


Once you understand how the coordinates system works in the p5.js library, all that’s left to do is create the shapes you want, and loop them into place.


There are two important things to keep in mind when deciding how to space everything out in your canvas (aka your browser):


   1. The top left corner is equal to the position of 0,0 pixels, and grows out in positive increments (figure 2).


   2. Any plotted or set position on the canvas has it’s own cartesian coordinate ‘sub-plane’*, however this cartesian 'sub-plane’ resembles the OG coordinate system (figure 1). So within figure 2’s spaciality, you can have many smaller system’s resembling figure 1.


If that makes no sense to you, give this a look and see if anything clicks:



As you can tell, in the above case, my canvas isn’t the size of my whole browser - I’ve restricted it to 400 pixels by 400 pixels to keep the example simple. In the draw section, I’ve done three things:


    1. used nested for loops to plot out the pixel location for every 50 pixels across the canvas’ width (x) and the canvas’ length (y) up to 50 pixels before the edge of each.


    2. marked each plotted pixel location with an X, which I’ve drawn by generating two lines.


        3. calculated the location of each line’s start and end point using the plotted pixel location as the center of the sub-plane (aka the position of 0,0 pixels in relation to the plotted pixel location || the center of the X, where the two lines cross)


With that in mind, take a look at the code I’ve written to port my image:


Once again, the original:


image


And here is the ported version:


image



*for lack of a better term.

It Will All Make Sense Later #2: Objects

As someone who didn’t start with JS when first learning to code, since making the jump, I’ve found myself constantly comparing JS concepts to their Ruby or Python equivalent. It feels like a very natural thing to do with any language - programing or spoken. It helps us find our bearings and allows us to build our own context for understanding. But while these types of comparisons often help learners equate syntax discrepancies, sometimes it can cause more confusion than clarification.


Case in point: I hate hashes in Ruby. With a bit of a pronounced passion… I couldn’t tell you exactly why, but I find using them to be really awkward (yes, I know this is weird because, yes, the hash is a pretty basic concept. But alas, it has yet to win over my heart.) So maybe one day I’ll learn to love the dreaded Ruby hash, but until then, when it comes to objects in JS I’ll focus my understanding on comparison-free definitions.


So what is an object in JS & how does a n00b coder use it?


Well, an object is actually just any regular old variable, with one exception: it can simultaneously contain many items.


//a variable:

var unicorny = ' A feature so early in its planning stages that it might as well be imaginary.' // an object:
var unicorny = {
    definition: 'A feature so early in its planning stages that it might as well be imaginary.',
    origin: 'programming jargon'
}


Think of an object as a list that contains items. Now imagine that each item is represented by a property/value association.


Easy enough, right? I mean, what we have is basically a variable name representing the contents of a list, in which each item is defined by a property/value set.


Now for the messy part: accessing elements of the object.


It all starts off innocently enough: since the values are written as property/value pairs, we can use [ ] or . to access the values of the items inside the object.


But each mode of access is used in a specific case:
-use . when you know the name of the property of the item you’re trying to access


var unicorn = {

    name: 'JS',
    age: '21'
};

var js = unicorn.name; // JS
var twentyone = unicorn.age; // 21


-use [ ] when the value’s property contains a space or…


 var unicorn = {

   'name': 'JS',
    'age': '21'
};

unicorn['name']; // JS
unicorn['age']; // 21


…(and now for the messy part,) when you want to access a property whose key is stored in a variable.


var someProp = 'propName';

var myObj = {
    propName: 'Some Value'
}

myObj[someProp]; // 'Some Value"


The first time I saw this, I got really annoyed because when I read it, it seemed to me that myObj[someProp] should return “propName” but when I tried it out in my console, it indeed returned “Some Value’.


It all clicked for me when I swapped an = for a === and looked at equivalencies:


myObj[someProp] ===myObj.propName;


A friend had pointed out that when it comes to accessing a property whose keyword is a variable, calling myObj[someProp] allows you to ACCESS the items value.


Think about that word for a sec, ‘access,’: since the item’s value is a variable, and a variable actually represents something other than itself, what you’re accessing is what’s inside the variable, which in this case is "propName”, which if you remember, is also a property in an item in the myObj object.


So if we look back at the unicorn object example, things become more clear doesn’t it? :


var unicornName = 'JS';

var unicorn = {
    JS: 'Java Script'
}

unicorn[unicornName]; // 'JS'


With that in mind, hopefully this can help dispel some of the confusion people might be having when trying to access objects. It might not seem that important, but understanding why you access an object using square brackets or dot notation will go a ways in helping you wrestle with things likes JSON files down the line.

It Will All Make Sense Later #1

When I first switched from learning to code in Ruby (which is a really beautiful language but one that doesn’t do much for the more front-end-obsessed like myself) to learning to code in JS, I had some trouble adjusting to the way JS deals with scope. Before I get into why, let’s look at what scope actually is.


While anyone can easily find a generic, sterile, scope definition with a quick Google search, I perfer my own. I think of it like a distinct universe within which a certain chunk of code is contained. The various elements at play within said chunk of code have a specific reach, which extends the breadth of the code chunk. That reach? That’s what scope is. Since the element’s scope can’t access anything outside of that chunk of code, the elements are ‘invisible’ to the rest of your code, and can’t be used by any other code chunks that you may have written.


Well, most of the time…Wait, wait, what? Most of the time aka, not all the time?


Let’s consider global versus local variables for a second. For a variable to be considered global, it must be declared outside any code blocks. We can then safely agree that a local variable would be one that is contained within a code block, yes? But again: not always. What if, when declaring a variable within a block of code, we drop the 'var’ keyword? What happens?


// both variables are global
var unicorns = 1;
farts = 2;

function(){
    var unicorns = 1; // Local
    farts = 2;     // Global

    //anonymous function
    (function(){
        var charms = 1; // local
        unicorns = 2; // inherits from the function's encompassing scope
        pixels = 3; // global
    }())
}


Did you know that in JS, if you declare a variable without using the 'var’ keyword, your variable is considered global? This might seem like a small detail to the more seasoned JS devs out there, but as I switched from Ruby, a language that doesn’t require the 'var’ keyword in front of any of it’s variables, to JS, where it’s considered good form to always use 'var’, you can imagine the kind of bugs I ran into.


An important thing to keep in mind if you plan on playing around with using var: if you’re not assigning anything to the variable you’re declaring, you have to use the 'var’ keyword:


var x;


If you’re curious about the more intricate differences between variables declared with and without 'var’, check out this blurb I came across in my research:


var x = 10
x = 10

The difference between the two variables is subtle and might be confusing unless you understand that variable declarations also create properties (only on a Variable Object) and that every property in Javascript (well, ECMAScript) have certain flags that describe their properties - ReadOnly, DontEnum and DontDelete.
Since variable declaration creates property with the DontDelete flag, the difference between var x = 1 and x = 1 (when executed in global scope) is that the former one - variable declaration - creates the DontDelete'able property, and latter one doesn’t. As a consequence, the property created via this implicit assignment can then be deleted from the global object, and the former one - the one created via variable declaration - cannot be deleted. - source

Review, readjust, continue

Last week I set up a pretty basic drawing app. Click, and draw. Easy. But as I set out to create the color options that I wanted to include I realized that I’d forgotten to account for the space I’d need within my canvas for each color swatch, and most importantly, I’d need a specified area where all the drawing could happen.


One of the best parts of the p5.js library is that it can turn your entire web brwoser into a blank canvas. But that can often lead to people (a.k.a me,) pumping out lines of code before properly hashing out their idea on paper. It’s an important step that can really help reveal potential snags in your original concept.


Case in point: I’ve always used P5 in my entire browser, so I didn’t naturally account for certain things a simple mock up would have pointed out for me regarding sizing and spaciality.


image


With P5, you can set specific width and height measurements (in pixels, of course,) and create a smaller canvas within your browser. Originally, I’d created a 400px by 400px canvas, so to create space for each color swatch, I simply extended the height of the canvas by 100px.


Next, I created the area where the drawing could take place, which was a bit of a trickier exercize. First step, draw the space. Easy enough: create a rectangle, starting and (20, 20), ending at (360,380) within the canvas. Second step, contain anything you draw within that space. A little trickier…



I wresteled with methods map and dist for a while, before defaulting to a simpler option: the trusty && operator. I’ve commented all of my code below, so hopefuly you can get an idea of what’s happening under the hood. Next up? Color swatches.


Setting up the basics

So, I’ve thrown together the most basic of programs to start off my simple drawing app. For now I’ve just built a working skeleton: when the user presses the mouse within the container, they can draw something - always with a default color of black. Go ahead and try it!



first steps:
1. create canvas space in center of page
2. on mousepress, leave mark on screen
3. create color & stamp choices - centered, directly under canvas space
4. on mousepress, mouse to draw in chosen color/stamp
– 4.1 create icons for colors (3) and stamps (2)
– 4.2 create eraser/undo tool to step backwards through your creation (layers?)


If you’ve never looked at the P5.js library, it’s definitely worth a peek. Especially if you’re interested in building visual, dynamic things in the browser. Here, with just a few quick lines of code, I’ve already got myself a nice little canvas to start adding to. As things get more complex, I’ll walk through the code. But for now, see if any of it makes sense to you.


function setup() {
  createCanvas(400, 400);
}



function draw() {
  if (mouseIsPressed) {
  fill(0);
  ellipse(mouseX, mouseY, 20, 20);
  } 
}

01.16

P5 PAINT


a simple paint program, coded in javascript.


first steps:

1. create canvas space in center of page
2. on mousepress, leave mark on screen
3. create color & stamp choices - centered, directly under canvas space
4. on mousepress, mouse to draw in chosen color/stamp
– 4.1 create icons for colors (3) and stamps (2)
– 4.2 create eraser/undo tool to step backwards through your creation (layers?)