YOUR GUIDE TO

Coding Concepts with the Colorful Canvas

Coding has about as many rules as chess

Welcome readers from ◎ Your Guide to Coding Creativity on the Canvas

Image for post
Image for post
ZIM Intro example demonstrating aspects of coding

ode contains the instructions that we give the computer to run an app such as a game, tool, art, puzzle, visualization, etc. In this guide we show the basic parts of coding and demonstrate these in a colorful way on the canvas!

We say colorful, because often, people are taught code using a console — so they see only text which can be a little boring for visual learners.

One distinction we should make is that HTML and CSS, which make Web pages, are called code as well. These two are tagging languages and are missing the logic and dynamic aspects that come with traditional coding. This is a reason that we sometimes use the term programming rather than coding.

Overview of Parts of Code

here are three main areas of code. We have listed these and their parts below. The number of things to keep track of as you code is very similar in memory and understanding to that of playing chess. Of course, chess is a game where as code provides a much broader opportunity for expression! You are free to make the world!

  1. SYNTAX
    keywords, statements, expressions, operators
  2. OBJECT ORIENTED BASICS
    classes, objects, properties, methods, events
  3. PROGRAMMING BASICS
    variables, functions, conditionals, loops, arrays, object literals

YOU ARE IN LUCK! Rather than break these down and explore each one, as many programming teaching resources will do, we are going to take a more holistic approach and just get coding some visual examples. We will look at the Syntax and Object Oriented Basics in this guide. As we use these parts above we will discuss them. Let’s call it:

throwing you in at the shallow end!

Programming Languages and Coding the Canvas

here are many programming languages such as JavaScript, PHP, C++, Python, Ruby, Java, etc. These share the three parts of coding listed above with minor differences. We will use JavaScript, the most popular programming language. It is free and works in the Browser. We are going to code the JavaScript Canvas.

Please see ◎ Your Guide to Setting up an Editor and Template to Code on the Canvas for more details but we will guide you below on how to test your code.

Shapes on the Canvas

et’s regress. Shake off any worries and spend some time enjoying exploration, like when we were kids. As it happens, you are going to code in a Kids’ online editor ;-). Do not worry, in the end, this code can be used in a completely professional way.

If you prefer a video tutorial (then why are you on Medium!) then the video below shows a rough equivalent to what we are doing here. OOP, by the way, means Object Oriented Programming. Please note that this is a series: Learn JavaScript with Creative Coding so you can check out other videos in the series as desired.

See the Video on YouTube for Chapters

A ◈ Open up the ZIM Kids Editor. You may want to set the editing window at the right using the little icon at the bottom left.

Image for post
Image for post
ZIM Kids Editor

B ◈ Type or copy the following into the editor:

new Rectangle(300, 300, red).center();

With respect to coding syntax, this is called a statement - it tells the computer what to do. Generally, the statements run one after the other. You can read more about the structure of a statement, and indeed about any of what we are writing about, in the Magic section of ZIM Kids. Or in Lesson 01 of ZIM Skool. Or in the What IZ? series in the ZIM Learn section.

Image for post
Image for post
// Here is your code
new Rectangle(300, 300, red).center();

In our code, we also have a class called Rectangle. A class holds the code or instructions to make an object. By convention, a class starts with an uppercase letter. We use the new keyword to make an object from the class. An object is just like in life — a thing — and forms the basis of object oriented programming. We can make as many objects as we want this way. In the round brackets ( ) we can give the class more information about how to make the object. These are called parameters. The parameter values we pass in are called arguments. Here we want the rectangle object to be 300 pixels wide and 300 pixels high and to be the color red.

C ◈ Objects can have properties and methods. Properties describe the object, like an adjective, or they are things the object has. Examples are width, height, rotation, color, etc. Methods are something the object does, like a verb, or something that is done to the object. Examples are play(), stop(), animate(), etc.

Let’s try changing a property. Adjust the code as follows:

const rect = new Rectangle(300, 300, red).center();
rect.color = purple;

Here we set the color property of the object to purple. We use the dot syntax so put the object, then a dot (.) and then the property. We then use the assignment operator (=) to assign a new color. Of course, we could have just made the rectangle purple to start!

Image for post
Image for post

Note, that to access the rectangle we had to assign (=) the rectangle object to a constant we called rect. In earlier versions of JavaScript we would use var for variable. A variable is a name that we make up to refer to an object so we can use it later. It is like putting a label on box to say what is inside. It is called a variable because the object may change later. In the latest version of JavaScript, we use const for a variable that does not change the object that it holds. So not really a variable, is it. We use let for a variable that will change. Using var still works and many examples out there use var but now const and let are preferred.

We also have a method called center(). You can tell a method because it is dotted to the object, like a property, but it ends with round brackets (). The method tells the object to be centered on the stage.

D ◈ Sometimes it is hard to tell why something is a method or a property. For instance type below to change the location of the object:

rect.x = 100;
rect.y = 100;

The x and y are properties of a Rectangle object (and any Display Object). The x and y are 0 at the top left corner and get bigger going to the right for x and down for y (not up, like in math).

Image for post
Image for post

However, we can also use the loc() method to locate the object. Try this:

rect.loc(200,200);

The loc() method places an object at an x and y. So… why would we have two ways? And which would we choose? Not every property has a method and visa versa. If you wanted to find out where the rectangle is then we would use the x and y properties. If we want to set the properties, we can use either. There is an advantage to using loc() as we will demonstrate below.

E ◈ Comment out all your code. To do this, select the code and press CTRL/⌘ and then / for comment. This will add // to all of the selected lines. To uncomment just select and do the hot keys again.

After the commented code type the following:

new Rectangle(300, 300, pink).loc(20,20).drag();

Here we use loc() and we do not have to assign the rectangle to a constant. This saves us lines of code. We can also do what is called chaining. This is where we continue to dot (.) methods onto methods as we have done with the drag() method above. The methods need to be made in a particular way for this to work. They return the object. But this is more than you need to know for now.

Section Summary

here were certainly a lot of words and definitions in this section relating to Coding syntax, object oriented basics and a few programming basics. We will use these terms often so you will get used to them. Perhaps after reading the article and trying out some code, come back and read the article again. You will be surprised that it becomes more clear each read.

DOCUMENTATION for all the commands is here: ZIM Docs

Remember that further resources are available in the Video on YouTube and the Magic section of ZIM Kids. Or in Lesson 01 of ZIM Skool. Or in the What IZ? series in the ZIM Learn section.

Image for post
Image for post
The What IZ video series on parts of code

Transformations on the Canvas

Image for post
Image for post
A rectangle rotated around its registration point

A transform is a term that we use to mean a changes in the following properties (ZIM chainable methods also shown). These are very basic properties and important to make our DisplayObjects look how we want.

  1. Position
    x, y
    loc(x,y), pos(x,y,h,v), mov(x,y), center(), centerReg()
  2. Scale
    scaleX, scaleY
    sca(scaleX,scaleY), siz(width, height)
  3. Rotation
    rotation
    rot(degrees)
  4. Registration
    regX, regY
    reg(regX, regY)
  5. Skew
    skewX, skewY
    ske(skewX, skewY)
  6. Transparency (not an official vector transformation)
    alpha
    alp(alpha)

Here is a video that takes you through the concepts we are about to discuss.

See video on YouTube for chapters

A ◈ In the ZIM Kids Editor you can CLEAR any previous code and type:

new Circle(200, blue).center().outline();

The outline() method is used when we are building to show information. We would not usually show the outline in the final project.

Image for post
Image for post

Here we can see a red bounding box placed around the circle. These represent the bounds of the shape which are a rectangle with x, y, width and height. All ZIM shapes and components have bounds set. Bounds are required to be able to get or set widths and heights. They are important when using hitTestBounds(), a common hit test, and also when using pos() to position something relative to the edge of the screen.

B ◈The round red circle in the middle is called the registration point. This is the point about which the object will scale and rotate. Also, when you place an object at an x and y, the object is placed so its registration point is at the x and y. Try scaling the object like this:

new Circle(200, blue).center().outline().sca(.5);
Image for post
Image for post
Circle scaled at half its original size

Note that the outline() is like a snapshot in time. So we scale after we outline which is different than this:

new Circle(200, blue).center().sca(.5).outline();
Image for post
Image for post
Circle scaled then outlined

C ◈Let’s take a look at a Rectangle, which will behave like other rectangular objects like buttons and bitmaps (pictures). CLEAR your code and type this. Note that we can put chaining on multiple lines! We usually tab in the chained properties but in this article we will use two spaces. You should use tabs.

new Rectangle(300,300, yellow)
.center()
.outline();
Image for post
Image for post

Note that the registration point is at the top left corner. This means that the rectangle will expand out from this point when scaled. Try this:

new Rectangle(300,300, yellow)
.center()
.outline()
.sca(1.5);
Image for post
Image for post
The rectangle scales from its registration point

D ◈Let’s try rotating the rectangle. Comment out the scaling from the last step and rotate the rectangle as follows. Note we have moved the semi colon (;) to the end.

new Rectangle(300,300, yellow)
.center()
.outline()
//.sca(1.5)
.rot(45);
Image for post
Image for post
The rectangle rotates around its registration point

E ◈ You can change the registration point with reg() although the most common need to change the registration point is to center the registration point on a Rectangle or Bitmap image. Adjust your code to use centerReg():

new Rectangle(300,300, yellow)
.centerReg()
.outline()
//.sca(1.5)
.rot(45);
Image for post
Image for post
Rotated Rectangle with centerReg()

See how the registration point red circle is in the middle. This is important when animating the rotation of scale. Usually we want the rectangle to rotate or scale about the center. Here is a CodePen demo on Registration Point.

F ◈ We can also use addTo() which just places the object on the stage at 0,0 but we usually use center(), centerReg() or loc(). The last way to position is using pos(). This is very handy to place an object a distance from any edge or from the center. If you know CSS, this is like left, top, right, bottom but we also have center. CLEAR your code and type:

new Rectangle(300,200, orange, white, 5)
.pos(50,50,RIGHT,BOTTOM);
Image for post
Image for post
A Rectangle positioned 50 pixels from right and bottom with pos()

pos(x,y,h,v) lets you position the object at an x and y distance from the horizontal (LEFT, CENTER, RIGHT) and vertical (TOP, CENTER, BOTTOM) with LEFT and TOP being the defaults. Note that it does not position the registration point but rather the edge of the object (or center with CENTER). Here is a CodePen Demo page on Positioning.

G ◈ Here is a list of other shapes that you can try that pretty well work the same way. You can try each one in the editor. CLEAR the editor each time.

new Poly().center(); // pentagon
new Poly(200, 5, .6, pink).center(); // five point star
new Blob().sca(2).center();
new Squiggle().sca(2).center();
new Line().center();
new Line(300, 30, purple, null, "arrow").center();
new Flare().center();
Image for post
Image for post
A Line on the canvas with an arrow.

H ◈ Finally, there is a custom shape as well. This is a little different as the Shape object does not have all the methods and properties that the ZIM shapes have but it allows us to draw any shape. This is similar to raw canvas where you have to draw all your shapes like this. As you can see, this takes more code to draw shapes You can try out this code:

const shape = new Shape().addTo();// a line
shape.graphics
.beginStroke(blue)
.setStrokeStyle(10)
.moveTo(200,200)
.lineTo(400,200);
// a rectangle
shape.graphics
.beginFill(red)
.drawRect(400,100,200,200);
Image for post
Image for post
Custom Shape

Containers on the Canvas

special DisplayObject is a Container. A container is invisible and can hold other DisplayObjects like shapes, components and other Containers. A Container is similar to a div tag in HTML.

Containers allows us to nest objects and gives us a hierarchy known in Flash as a Display List, in gaming as a Scene Graph, in HTML as a DOM (Document Object Model) and on the Canvas as a BOM (Bitmap Object Model).

CLEAR your code and type this:

const triangles = new Container();
new Triangle().addTo(triangles);
new Triangle().addTo(triangles).mov(100);
new Triangle().addTo(triangles).mov(200);
triangles
.sca(3)
.alp(.5)
.pos(0,100,CENTER,BOTTOM);
Image for post
Image for post
Triangles added to a Container to make mountains!

We could have used a Tile() to create these more easily. A Tile is a container but it does the tiling of objects for you! See ◎ Your Guide to Coding Creativity on the Canvas and locate Tile - which is in another Guide.

Note that we positioned the container after we added things to it. We have also transformed the container and all its contents get transformed at once! There are other handy reasons to use containers as we will see in other Guides.

Objects inside a container are called its children and the container is the parent. A container will automatically grow to put bounds around its children unless you give the container dimensions to start.

Here we make a container the size of the stage and then add three objects to the container. Note how we pass in the container to the methods as parameters. Otherwise the objects would, by default, be added to the stage. You can think of the stage as the base container.

const holder = new Container(stageW, stageH).addTo();
new Rectangle().center(holder);
new Circle().pos(50,50,LEFT,BOTTOM,holder);
new Triangle().loc(900,100,holder);
Image for post
Image for post
Three objects in a Container on the stage

CONCLUSION

this guide, we have seen how to get shapes on the Canvas and transform them. We have also introduced the Syntax of code and the Object Oriented Basics of classes, objects, properties and events. A good thing is that all DisplayObjects work this way including components.

Further reading

See ◎ Your Guide to Components on the Canvas with JavaScript where we also explore Programming Basics.

The canvas is a great place to code creativity. The canvas is also super for learning to code as we get colorful results right away. Please read ◎ Your Guide to Coding Creativity on the Canvas if you have not yet. This overall guide has links to the individual guides of which this guide is a part. Isn’t it nice to be part of something! You are welcome to join us on the ZIM Slack for community and questions!

All the best! Dr Abstract.

Image for post
Image for post

Follow us on Twitter at ZIM Learn and here is ZIM Learn on YouTube!

Written by

Inventor, Founder of ZIM JavaScript Canvas Framework and Nodism, Professor of Interactive Media at Sheridan, Canadian New Media Awards Programmer and Educator