ZIM KIDS - MAGIC
Icons showing ZIM Examples such as a space guy with domed helmet against pink sky and a rolling droid game to turn off energy shields next to moving blobs of color that animate to sound next to a game to move little bugs on paths to collect sugar and avoid teacups.  Then there are several dozen more magical examples!

Coding Magic

JavaScript Canvas for Schools, Coding Camps and Workshops

INTRO

Programming is like magic.

You can make objects appear and disappear.

You can animate and wiggle them.

You can control and explode them!

Press the wand menus below to see how to use spells to make Magic!

Here is a link to the  SPELLS

1. DISPLAY OBJECTS

SHOW ▼︎
a picture showing lines that are drawn by making circles turn inside of circles.  These make beautiful looping patterns like lace or spider webs or braids of hair!

Display objects are things you can see when they are on the stage (the screen). Examples are shapes, components (labels, buttons, etc.) and images.

An object is made from a class - which has the instructions or ingredients for the object. Use the new keyword to make the object from its class.

01
new Circle(50, red)

We can make the object do something with a method, which is like a verb. Here, we center the object on the stage and make it draggable. We use a dot to separate the object and the methods. At the end of the line is a semi-colon (;) that ends the statement.

02
new Circle(50, red).center().drag();

Sometimes we have to use an object later so we store it in a variable. Then we can change a property of the object. Properties are like adjectives.

03
var button = new Button().pos(100, 100);
button.enabled = false;  // turn off the button

// Class names start with a capital letter
// Variable names should start with lower case
// They can't have spaces so we use camelCase ;-)

// In JavaScript 6 we can optionally use const and let
const name = "Dr Abstract"; // will not change
let age = 50; // will unfortunately change
// We use var in the tutorials for simplicity

Statements usually run in order to make the magic happen! Here are parts that a statement can have:

a picture showing the parts of a code statement.  The statement is var answer = 31 + 15 semicolon.  Var is the keyword, answer is the identifier, = is the operator, 31 + 15 is the expression, semicolon is the terminator (cool) and the whole thing is the statement.

The characters, words and order they are written is called syntax. Code will not work if syntax is broken. We call this a bug (but not the cute yellow bug in our tutorial). Bugs are quite common so you will have to summon patience! Think of coding as the world's greatest puzzle and feel rewarded when it works!

ZIM Skool - JavaScript Coding Lessons for Kids, teens and all!  This link takes you to another site called ZIM Skool with more in-depth lessons for coding. See MORE at ZIM Skool!

2. PARAMETERS AND ANIMATION

SHOW ▼︎
a picture showing parameters of a rectangle.  These are placed in round brackets and are width, height, color, etc. to tell more information about the rectangle.  The parameters can be found in the Spells section where a hundred spells are many having dozens of parameters.

Parameters can be used by an object or a method to receive extra information. We send arguments to the parameters inside round brackets () and they must be in the order shown in the Spell list.

04
new Rectangle(100, 50, blue, green, 10, 20)
    .center(building); // a new line is fine for dots

// 100 and 50 are arguments for the width and height parameters
// blue and green are the color and borderColor
// 10 and 20 are the borderWidth and corner
// building (must exist) is a container
// Containers can hold any number of objects

If you want to use the default values you can write null or undefined in JavaScript 6. You must keep the order and you can't just leave parameters blank.

05
new Rectangle(100, 50, blue, null, null, 20)
    .center(building);

// do not provide a borderColor and borderWidth

It can be annoying to count the number of nulls. So we have a second way to make parameters. We can use a configuration object { } as a single parameter:

06
new Rectangle({
    width:100, height:50, color:blue, corner:20
}).center(building);

// {parameter:value, parameter:value, etc.}
// ** the order does not matter
// ** can be on one line or lots of lines

ANIMATION

This picture shows six different features of ZIM animate.  Absolute, relative, series, from, wait and sequence.  These make an object animate in different ways.

We often use a configuration object when we animate things to make them move, spin, fade out, or scale bigger, loop and rewind!

07
new Rectangle(100,100,green)
    .centerReg() // will now animate around middle
    .animate({
        props:{scale:2}, // can animate more than one property
        time:1,          // one second ***
        rewind:true,     // get bigger then smaller
        loop:true        // keep doing animation
    });

    // *** For a long time in ZIM, time was in milliseconds
    // so 1000 ms would be 1 second - older examples will still be like this
    // Now, in ZIM CAT, time is in seconds to make it easier for us!
    // Or setting TIME = "milliseconds" would set it back

See the ANIMATE page for all sorts of animation options!

ZIM Skool - JavaScript Coding Lessons for Kids, teens and all!  This link takes you to another site called ZIM Skool with more in-depth lessons for coding. See MORE at ZIM Skool!

3. FUNCTIONS AND EVENTS

SHOW ▼︎
a picture showing a list of example functions such as shuffle, rand, loop and a dozen more.

A function is a block of code that you can run whenever you want and as many times as you want. An example would be to explode an asteroid. You can make (define) your own function:

08
function greet(message, location) {
    new Label("hi").pos(rand(200,800), 500);
    // put as many statements as you want here!
    // the { } are called a "block of code"
    // they are like a box that holds the code to run
    // we indent to easily see what is in the function
}

// a function must be called to run
greet(); // call (run) the function - a label gets added
greet(); // call the function again - another label gets added

// rand() is a function to get a random number
// pos() is a special function - a method - stored on the object
// note that pos() is dotted to the object and rand() is not

Arguments can be passed to the function parameters.

09
function greet(message, location) {
    new Label(message).pos(location, 500);
}
greet("hello", 200); // Label says hello at x=200
greet("goodbye", 600); // second Label says goodbye at x=600

EVENTS

An event is when something happens. This is the magic of interactivity!

Example Events

  • click
  • pressdown / mousedown
  • pressmove
  • pressup
  • change
  • complete
We use the on() method which has TWO parameters we will use:
   1. the type of event
   2. a function to call when the event happens

10
var button = new Button().center();
button.on("click", go);
function go() {
    zgo("https://zimjs.com"); // short ZIM function to go to URL
}

Often we use a anonymous function (function literal) as the second argument of the on() method:

11
// ANONYMOUS FUNCTION
var button = new Button().center();
button.on("click", function() { // use a function with no name
    zgo("https://zimjs.com");
}); // note the closing round bracket

// ARROW FUNCTION
// JavaScript 6 has an arrow function
// that is like an anonymous function.
button.on("click", ()=>{ // an arrow function in JavaScript 6
    zgo("https://zimjs.com");
});

ZIM Skool - JavaScript Coding Lessons for Kids, teens and all!  This link takes you to another site called ZIM Skool with more in-depth lessons for coding. See MORE at ZIM Skool!

4. ARRAYS AND LOOPS

SHOW ▼︎
The picture shows the same code as in the content below for arrays and loops.

An Array holds a list of things in [ ] that we can access by index number that starts at 0.

12
var colors = [pink, orange, red, green, blue];

var firstColor = colors[0]; // gets the first color, pink

new Circle(90, firstColor).center(); // a pink circle
new Circle(50, colors[2]).center(); // with a red circle on top

// we can use the length property of an array too
new Circle(20, colors[colors.length-1]).center(); // blue on top

// we can change colors, add colors, sort, shuffle and more!
colors[1] = brown; // the second color is now brown
colors.push(grey); // grey has been added to the end
colors.sort(); // alphabetical order using sort() method
shuffle(colors); // ZIM function to randomize array

LOOPS

A loop repeats a block of code between { } as many times as you want:

13
loop(10, function() {
    new Triangle().center().drag(); // 10 draggable black triangles!
});

loop(10, function(i) {
    // i increases each loop - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
    new Triangle().pos(100+i*100, 500);
    // 10 triangles spaced by 100 pixels across the stage
});

We can also loop through an array!

14
var colors = [red, orange, yellow, green, blue, pink];
loop(colors, function(color, i) {
    // color will be red, then orange, then yellow, etc.
    new Rectangle(50, 50, color).pos(20+i*60, 20);
});
this shows the colors red, orange, yellow, green, blue and pink that matches the array.  Red looks rough, orange is smoother and yellow is very smooth.  Green looks fresh and blue looks wet or airy and pink looks soft or tastes like strawberries.

And loop through a Container:

15
// the rectangles are now on the stage which is a container
loop(stage, function(object) {
    object.sca(.5); // makes each rectangle half as big
});

These examples are with the ZIM Loop. There are also for loops and while loops. These are common to all programming languages do similar things but with different syntax. See the MORE link for examples.

ZIM Skool - JavaScript Coding Lessons for Kids, teens and all!  This link takes you to another site called ZIM Skool with more in-depth lessons for coding. See MORE at ZIM Skool!

5. CONDITIONALS AND DEBUGGING

SHOW ▼︎
a picture of the ornamator which was made with conditionals and took lots of debugging!

Programming uses logic to determine what happens. Another word for this is a conditional or an if statement.

16
if (circle.color == blue) {
    circle.alp(.5);
}

// this compares the colors and if equal (==) then
// sets the alpha (transparency) of the circle to half

You can do something else if the condition is false:

17
if (circle.color == blue) {
    circle.alp(.5);
} else {
    circle.alp(0); // hide the circle
}

You can also do multiple conditions:

18
if (circle.color == blue) {
    circle.color = black; // change color to black
} else if (circle.color = red) {
    circle.color = white; // change color to white
} // could add another else if () {} or an else {}

DEBUGGING

When the code breaks you will probably see an error message. Here are some common bugs:

Syntax Errors

  1. Forgot to end a quote " ' ` or a bracket ( { [
  2. Too many brackets (selecting a bracket highlights its match)
  3. Using a keyword that does not exist
  4. Typos - spelled a keyword incorrectly
  5. Using an undefined variable in an expression
  6. Using a bad character (-+*&, etc.) in a variable name
  7. missing comma (,) or colon (:) in array or object literal

If nothing shows up - here are some things to check for:

Nothing Shows

  1. The Internet is down
  2. You forgot to add object to the stage - use addTo(), center(), centerReg()
  3. You forgot to put stage.update() at the end of an event function
  4. When adding to a container, remember to add the container to the stage
  5. You are viewing the wrong file

ZIM Skool - JavaScript Coding Lessons for Kids, teens and all!  This link takes you to another site called ZIM Skool with more in-depth lessons for coding. See MORE at ZIM Skool!

6. CONTROLS

SHOW ▼︎
a dozen small pictures of ZIM controls with Pragma, Dr Abstract's daughter sitting crosslegged on a bright pink box next to them.  She is happy because the controls lets you do things easily!  The first control is accessibility for screen readers.  The second lets you swipe things with your finger.  Then there are pages, controls to change the size and rotation, parallax for 3D effects, controls for animations, motion controllers, emitters of particles, animating to sound, a portal from one place to another, and virtual reality controls!

Controls help you do things with one or more objects. We will look at a few but there are many more.

19
var circle = new Circle(50, red).center();
new MotionController(circle);

// the circle will move to where you press on stage
// add ,"mousemove" to make the circle follow your mouse
// or use "keydown", "gamebutton", "gamestick", or "swipe"

You can use a Ticker to constantly check for something:

20
var rectangle = new Rectangle().pos(100, 100);
Ticker.add(function() {
    // assuming we are controlling the circle from above
    if (circle.hitTestCircleRect(rectangle)) {
        rectangle.removeFrom();
        // the Ticker automatically updates the stage
    }
});

Use an interval to keep on adding new rectangles. An interval is like a Ticker but you give it a time interval. There is also timeout which runs once after a certain time.

21
var rectangles = new Container().addTo();

// Every second add a new Rectangle randomly to the container
// Note - this is a ZIM interval with seconds first then the function.
// The JavaScript version is like this: setInterval(function, milliseconds).
interval(1, function() {
    new Rectangle().addTo(rectangles).pos(rand(stageW-100), rand(stageH-100));
});

// in a Ticker, loop through all the rectangles
Ticker.add(function() {
    loop(rectangles, function(rectangle) {
        if (circle.hitTestRect(rectangle)) {
            rectangle.removeFrom();
            // the Ticker automatically updates the stage
        }
    }, true); // loop backwards when removing
});
Another picture of ZIM controls - now we see that Pragma was sitting on the dot of the letter i in ZIM.  She is surrounded by an arch of words above that say the ZIM controls.  Dr Abstract presents the controls which are Accelerator, swiper, motionController, grid, guide, parallax, scroller, dynamo, accessibility, pages, hotspots and layouts.  More controls have been added since then too!  This is all part of the ZIM Foundation for Creative Coding and powered by CreateJS.  We hope to make coding magical for everyone!


CONCLUSION

Apprentice, you have seen the secrets of many apps and games!

Please continue to explore and have a great time coding.

challenge your friends to make amazing creations.

Start a coding club and let your teachers know about ZIM.

All the best, we love creative coders!


Pragma and Dr. Abstract

ZIM Skool - JavaScript Coding Lessons for Kids, teens and all!  This link takes you to another site called ZIM Skool with more in-depth lessons for coding. See MORE at ZIM Skool!