YOUR GUIDE TO

Components on the JavaScript Canvas

And an introduction to events and functions

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

Image for post
Samples of components on the Canvas MultiTouch Synth Pad

In this guide we will show you how to use components like Buttons, Sliders and Dials (oh my!) on the canvas in JavaScipt as well as the programming basics of functions and events used by most programming languages.

If you have not read ◎ Your Guide to Coding Concepts with the Canvas then you should have a read there first. These guides are part of ◎ Your Guide to Coding Creativity on the Canvas.

Overview of Parts of Code

There are three main areas of code as listed below. We have already seen the first two in the last guide (see the note above). We will continue to use these parts but we will concentrate on events and functions in this guide.

  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

Once again, 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 and talk about the parts as we get to them!

Components on the Canvas

Components are Display Objects such as buttons, labels, lists, sliders, etc. that provide the user with interface so they can send input and receive output. We will be using the components provided by the ZIM JavaScript Canvas Framework. To find out more, please see ◎ Your Guide to Selecting a JavaScript Canvas Library or Framework.

SKOOL!
A ◈ Let’s take you back to Skool — oh no! Don’t worry, click on ZIM Skool and go into Lesson 01. Scroll down until you see the practice section and open part 3 called Components. In the practice editor type the following code and press TEST:

new Label("Hello Medium Readers!").center();
Image for post
ZIM Skool Lesson 01 on Components

We have made a new Label object from the Label class. We passed a String argument (with quotes) into the Label parameters. We used the center() method to center the label on the stage. These coding basics were introduced in the ◎ Your Guide to Coding Concepts with the Canvas.

B ◈ Go the the second example by pressing the blue 2 button. These will take you through a bunch of quick easy examples of the components. We will not go through all of them, but you can at your leisure. There are also more components than shown here. You can find them all in the ZIM Docs.

Delete the label and type (and TEST) the following. Note that we are assigning the Button object to the constant button. A constant is like a variable but the object it holds does not change. The red and grey are for the backgroundColor and the rollBackgroundColor.

const button = new Button(250, 80, "EXPLODE", red, grey).center();
Image for post

C ◈ We press the button and nothing happens. Boo. Why does it not explode! Well, here is where the programming comes in. We will use a function. A function is a block of code that will run whenever it is called. Leave the button there and on the next line type:

function explode() {  
button.removeFrom();
stage.update();
}

This function will remove the button and update the stage so we see the change on the canvas. BUT… nothing will happen. We must run (call or execute) the function before the code will run. Add this after the last bracket and you will no longer see the button.

explode();

Well… that is not what we want! We want to remove the button when we press the button… and we really want to see it explode!

D ◈ comment out the explode() but putting // in front of it. We will use the on() method of the button to capture an event. An event is when something happens like a click, mouseover, load, keydown, etc.

Here is a list of common events: click, dblclick, mousedown, pressmove, pressup, mousemove, stagemousemove, mouseover, mouseout, ready, complete, change, keydown, keyup

The on() method has a first parameter that collects the type of event as a String (in quotes). The second parameter is what function to call when the event happens. Perfect! Type and TEST the following:

// explode();button.on("click", explode);

E ◈ Here is how you can make an explosion. Let’s see if you can figure out the right place to put this line of code:

new Emitter(new Rectangle(50,50,red)).center();

If you get the code in the right place, you should see it explode when we click the button. It will be quite the explosion. The explosion is constantly updating the stage so we no longer need the stage.update().

Here is the answer below. If you did not get where to put the Emitter… just remember, we do not always add code after the last line. In this case, if we did, the emitter would run right away.

Image for post
Explosion when the button is clicked

There are things that we would want to fix like adding a sound, making the explosion stop and perhaps mixing in some red colors. We will see how to do these things in other guides. Right now, we should focus a little on the Programming Basics. So let’s have a further look at functions.

F ◈ In JavaScript, we have what is called an anonymous function. This is a function with no name. Often coders are lazy (or efficient perhaps) so if we do not need to define a function with a name, we use an anonymous function:

button.on("click", function() {}); // when we want to add lines of code to the function:
button.on("click", function() {
// add a block of code here
// etc.
// etc.
}); // end the function and end the on() method

G ◈ In JavaScript 6 they introduced the arrow function format. This is now the preferred way to call an event function but you will see many older examples of the anonymous function and it still works and is fine to use if you want.

Here is the arrow function:

button.on("click", () => {}); // when we want to add lines of code to the function:
button.on("click", () => {
// add a block of code here
// etc.
// etc.
}); // end the function and end the on() method

Change your code to use an arrow function. And while we are at it, we will slip in a grey and red explosion (we will learn about it in the next guide):

const button = new Button(250, 80, "EXPLODE", red, grey).center();
button.on("click", ()=>{ // arrow function
button.removeFrom();
new Emitter(new Rectangle(50,50,[grey, red]))
.center();
});
Image for post
Event with JavaScript arrow function

Components with Change Events on the Canvas

The Button component gets mousedown or click events but most of the other components have a change event. Let’s try a few out. You can go to number 10 in the ZIM Skool Lesson 01 Components Practice section and delete your current code.

A ◈ Create a Circle and a Slider by typing this and pressing TEST:

const circle = new Circle(20, red).center();
const slider = new Slider().center();
Image for post

B ◈ The Slider has a min and max value of 0 to 10 and a currentValue property that starts at 0 but the current scale of the circle starts at 1. So we may want to either scale the circle to 0 to start or start the slider at a currentValue of 1. Either way is fine. It depends on how you want to start. Maybe starting both at 5 would be good. Let’s do that. Add this line which is a fancy way to set both of these properties to 5:

circle.scale = slider.currentValue = 5;
Image for post
Circle scale and Slider currentValue set to 5

C ◈ We want to make the circle change scale as the slider changes. We need to use a change event and have that call a function. In the function we will set the scale of the circle to the currentValue of the slider. Type this:

slider.on("change", ()=>{
circle.scale = slider.currentValue;
stage.update();
});
Image for post
Circle at scale and Slider currentValue at 10

Customizing Components on the Canvas

Components are very customizable in ZIM. Referring back to ◎ Your Guide to Coding Creativity on the Canvas, you will find other guides that discuss conveniences and how to apply STYLE. But we will take a look at the basics here.

Image for post
Variety of Buttons or Button settings in ZIM

You can make components look different to start using the many parameters. These are listed and described in the ZIM Docs. Open up the component to see the parameters described. Usually there is a width, height, color (font) backgroundColor, rollColor, rollBackgroundColor, borderColor, borderWidth, corner, etc. and many more, some are specific to the component. You can change the look of the component after its made by setting its properties. These are also listed in the docs.

// the first few Dial parameters
// min, max, step, width, backgroundColor, indicatorColor,...
// parameters go in order with null (or undefined)
// where you want to use the default value
new Dial(0, 20, null, 50, red, white, etc.);
Image for post

See the ZIM UI/UX banner section for more about ZIM Components. Also see the ZIM TEN feature site for components launched in ZIM TEN and ZIM Cat (the version after TEN) press the cat for the latest components.

Image for post
Image for post
Image for post
Components added in ZIM TEN
Image for post
Image for post
Image for post
Image for post
Image for post
Components in ZIM Cat — updated Dial and Slider, Scrambler and TextEditor

Last Words on Functions — Parameters, Scope and Return

We by-passed a few important aspects of functions. The first is how we can pass in arguments to a function and collect them in parameters. The second is scope which looks at where variables can be accessed. The third is that a function can return a value.

Parameters tell the function extra information. Here is a basic example where we collect two parameters called person and message. These are separated by a comma (,) and we can collect as many of these parameters as we need. We make up the name. They are like variables that we can use only inside the function. We pass in two arguments when we call the function. We use the plus (+) to join these strings together. This is called concatenation.

function greet(person, message) {
new Label(person + " says, " + message).center();
}
greet("Dr Abstract", "Aloha");
Image for post
Passing in arguments to parameters

Scope is the term we use to indicate where variables can be accessed. This is a little advanced, and takes getting used to. Here are the rules:

  1. A variable var can be accessed within the function it was made.
  2. A variable let can be accessed within the {} it was made.
  3. A const can be accessed within the {} it was made.

We have not really seen any other {} yet so for now, just keep the word scope in mind. Here is an example:

function add(a, b) {
let total = a + b;
}
add(10, 20);
new Label(total).center();
// this gives a scope error
// as total is only available inside the function

A solution to above would be to make the Label inside the function. Another solution is to return the total so we can use it outside the function:

function add(a, b) {
return a + b;
}
let total = add(10, 20);
new Label(total).center();
// this does not give an error
// the return value replaces the function call
// so we assign 30 to the variable total

CONCLUSION

We have taken a look at how to add components and capture their events to call functions. Of course coding is more than just putting things on the stage and capturing events. There is the logic to make it all work together. We are still seeing the parts so we need to be patient as all the pieces come together.

Image for post
Early set of ZIM Components.

Further reading

If you would like to see what coding is like on a Canvas Library or Framework here is ◎ Your Guide to Coding Creativity on the Canvas.

To learn more about Functions and Events there is the ZIM Kids Magic page for quick and easy details. The ZIM Skool Lesson 03 looks specifically at functions and events.

We hope you are enjoying the guides and if this is your first, please check out the other guide articles. Cheers!

Dr Abstract

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

Get the Medium app