
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!
With a little study, you will be able to make GAMES and APPS!
Here is a link to the SPELLS
1. DISPLAY OBJECTS
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.
new Circle(80, pink); // 80 is the size and pink is the color
We can make the object do something with a method, which is like a verb. Here, we center the object on the stage and move it to the left 200 pixels. 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.
new Circle(80, pink).center().mov(-200);
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.
var button = new Button().center(); 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 can use camelCase ;-) var myHat = new Pic("hat01").center().mov(200); // In JavaScript 6 we can optionally use const and let // Imagine that pink Circle with the Hat is Dr Abstract // const is for things that will not change const name = "Dr Abstract"; // let is for things that will (unfortunately) change! let age = 50; // 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:

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!
See MORE at ZIM Skool!
2. PARAMETERS AND ANIMATION

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.
var myBuilding = new Container(500,300); // Containers are invisible and are used to hold other objects. // Here we tell the container to be 500 in width and 300 in height. new Rectangle(100, 50, blue, green, 10, 20) .center(myBuilding); // 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 // we tell the center() method to center the rectangle in myBuilding
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.
new Rectangle(100, 50, blue, null, null, 20) .center(myBuilding); // do not provide a borderColor and borderWidth instead put null
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:
new Rectangle({ width:100, height:50, color:blue, corner:20 }).center(myBuilding); // {parameter:value, parameter:value, etc.} // ** the order does not matter // ** can be on one line or lots of lines
ANIMATION

We often use a configuration object when we animate things to make them move, spin, fade out, or scale bigger, loop and rewind!
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!
See MORE at ZIM Skool!
3. FUNCTIONS AND EVENTS

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:
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.
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
1. the type of event
2. a function to call when the event happens
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:
// 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"); });
See MORE at ZIM Skool!
4. ARRAYS AND LOOPS

An Array holds a list of things in [ ] that we can access by index number that starts at 0.
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 var color = pluck(colors); // ZIM function to pick randomly
LOOPS
A loop repeats a block of code between { } as many times as you want:
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().loc(100+i*100, 500); // 10 triangles spaced by 100 pixels across the stage });
We can also loop through an array!
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); });

And loop through a Container:
// 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.
See MORE at ZIM Skool!
5. CONDITIONALS AND DEBUGGING

Programming uses logic to determine what happens. Another word for this is a conditional or an if statement.
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:
if (circle.color == blue) { circle.alp(.5); } else { circle.alp(0); // hide the circle }
You can also do multiple conditions:
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
- Forgot to end a quote " ' ` or a bracket ( { [
- Too many brackets (selecting a bracket highlights its match)
- Using a keyword that does not exist
- Typos - spelled a keyword incorrectly
- Using an undefined variable in an expression
- Using a bad character (-+*&, etc.) in a variable name
- missing comma (,) or colon (:) in array or object literal
If nothing shows up - here are some things to check for:
Nothing Shows
- The Internet is down
- You forgot to add object to the stage - use addTo(), center(), centerReg()
- You forgot to put stage.update() at the end of an event function
- When adding to a container, remember to add the container to the stage
- You are viewing the wrong file
See MORE at ZIM Skool!
6. CONTROLS

Controls help you do things with one or more objects. We will look at a few but there are many more.
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:
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.
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 });

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
See MORE at ZIM Skool!