Javascript – all exercises

All the exercises we did during the course can be found here. This download includes all 5 exercises:

1 – hello world – getting familiar with Html, CSS and Javascript
2 – Drawing on canvas (including mouse and keyboard interaction)
3 – Arrays, Loops and Click-function to change the color of an item
4 – Javascript objects
5 – Bike price calculator

If you have any questions regarding these exercises or need help in completing your assignment you can contact me at mail at susemiessner dot org.

Additional materials for getting more familiar with Javascript can be found in the Material section of the course blog.



Posted in Uncategorized | Leave a comment

Javascript Day 03/04 – material

Bike image white
Bike image black


Prices and Names of the components:

size xs: 49cm  2949.00€
size s: 52cm  2959.00€
size m: 54cm  2969.00€
size l: 56cm  2979.00€
size xl: 58cm  2989.00€
size xxl: 60cm  2999.00€

DT Swiss R24 Spline  + 0.00€
DT Swiss R23 Spline  + 60.00 €

Ergon SMC-40 Sport Gel  + 0 €
Selle Italia Flite Monolink  + 44 €
Prologo Nago Evo Nack (Carbon Rail)  +100 €

Ritchey WCS Evo Curve  + 0 €
Ritchey WCS Road Streem II  + 102 €
Ritchey WCS Superlogic Carbon Evo Curve  +118 €
Profile Canta Ergo Drop UD BK Carbon  + 161 €

Posted in HTML5-JS | Leave a comment

Javascript Day 01

Tip #1: Coding equals constantly googling for answers.

What is JavaScript

In spite of their similar name, JavaScript has very little to do with Java, they still have the same roots in the family of programming languages and so the syntax looks a bit similar.

JavaScript was invented to add some dynamic functionality to web pages. Initially you could add some JS to straight into an HTML element to do some thing when a user clicks it. It was extremely limited, buggy and had huge cross browser issues.

You would load HTML and JavaScript from the server (e.g. PHP) and the browser would execute JavaScript to add increasingly complex dynamic functionality onto the web page. It was like this for many years.

A web page consists of JS, HTML, and CSS

The traditional separation of content and logic goes as follows:

  • HTML: contains  page structure
  • CSS: What the page looks like (Styling and layout)
  • Javascript (JS): contains logic of the website (adding or removing elements dynamically)
  • JS or CSS: can be used for animation


JavaScript and Processing

Many things in JavaScript work exactly the same as in Processing. There are however some differences that you should know that you will bump into.

JavaScript is a dynamically typed language. That means you don’t need to explicitly say what kind of type each variable is.

var numba = 5
var muumi = "pikkumyy"
var car = [10, 3, "wheels"]

Semicolons are optional in JavaScript. The two examples below are both valid JavaScript.

function sayPlusOne(number) {
    number = number + 1;
    console.log('Hello ' + number);
function sayPlusOne(number) {
    number = number + 1
    console.log('Hello ' + number)

Exercise 1: Hello world

This exercise consisted of an 3 files:

  • index.html
  • style.css
  • an image (in my case: wave.jpg)


<meta charset="utf-8">
<title>hello world!</title>
<link rel="stylesheet" href="style.css">

<div class="content">
<h1 id="title">Hello world!</h1>
<img src="wave.jpg">
<p>this is my website text.</p>
<div id="dynamic"></div>
<script type="text/javascript">
//alert("hello world!");
console.log("hello console!");

var myVariable="hello world!";
var mySecondVariable=20;
var myThirdVariable= 3.6*10/8;



var element = document.getElementById("dynamic");
element.innerHTML="this is a dynamic text";


    font-family: Arial;
    font-size: 16px;
    width: 100%;
    width: 400px;
    background-color: #d3d3d3;
    margin-left: auto;
    margin-right: auto;                

    padding-left: 10px;
    padding-right: 10px;
    padding-top: 10px;
    padding-bottom: 30px;
    text-align: center;

Remember that the CSS syntax can be part of the index.html file, however to keep things more clean it is good practice to separate CSS from HTML code. For simple projects it is also valid to keep the css inline by using

      background: grey;   

The styling should always be part of the head section of an html document, while Javascript should be the last thing in the body-tag
tag of the html.

Exercise 2: Drawing on Canvas (exercise still in process after Day 1)

In this exercise we used the canvas-element to draw different things in our html webpage. We then added a onmousemove function in javascript to track mouse movement.

Here is the code we ended up with in the end of Day1. We will continue this exercise  in our next session:


<meta charset="utf-8">
<title>canvas exercise</title>
<link rel="stylesheet" href="style.css">

<div class="content">
 <canvas id="myCanvas"></canvas>
<script type="text/javascript">
//get the element from our html document
 var canvas=document.getElementById("myCanvas");
 //this is a comment
 now you can write
 many lines of code
 they are all comments
 //get drawing context for the canvas
 var ctx = canvas.getContext('2d');
 //set the canvas width and height to the same as it's displayed width and height
 ctx.canvas.width = 400;
 ctx.canvas.height = 400;
 //draw a rectangle
 ctx.fillRect(20,20,100,50); // (upperLeftCornerX, upperLeftCornerY, with, height)
 //draw a line
 ctx.moveTo(50,100); //start the line from here
 ctx.lineTo(250, 70); //end point of the line

 //draw some text
 ctx.font= "48px Helvetica";
 ctx.fillText("hello canvas!",100,120);
 ctx.strokeText("hello canvas!", 100,180);
 //if mouse moves on canvas draw a circle around the mouse
 canvas.onmousemove = function(){
 //draw my movement
 //our first own function in JS
 function drawMovement(event){
 //here goes our function code;
 var x = event.clientX;
 var y = event.clientY;


    width: 400px;
    height: 400px;
    border: 1px solid black;


  • change the color of the circles drawn when you move your mouse depending on weather mouse button is down or up
  • draw mouse movement only if mouse button is down
  • make the canvas full screen on your browser window, no matter what is it’s size
Posted in Uncategorized | Leave a comment

Additional Processing exercises

More little Processing exercises. Not obligatory, just for rehearsing the topics we’ve covered. Example solutions included, but try first on your own.

  • Simple graphics. Create the familiar smiley face using the graphical capabilities offered by Processing. smileyface.pde
  • Variables. Declare two int variables with values 100 and 200. Print them, swap their values using a third variable and print again. swap.pde
  • Using the mouse. Make a crosshair that moves with the mouse. crosshair.pde
  • Loop and compare. Print all even numbers from 0 to 30, except 10 and 20. forbidden.pde
  • Animate and compare. Move a circle smoothly across the screen and change it to a rectangle in the middle. changemidway.pde
  • Arrays. For the first 100 frames, store the sum of mouse x and y coordinate in an array. savecoords.pde
  • Strings and arrays. Put five names into an array and print them on separate lines together with the line numer. names.pde
  • Functions. Turn the smiley face into a function that lets you plot it at any given location on the screen. Plot three of them to test it. smileys.pde
  • Return value. Make a function that takes two numbers as parameters and returns the bigger one. greater.pde
  • Random numbers, graphical text and type conversion. Create a font and load it. Each frame get a random number and display it at a random position. randomtext.pde
Posted in Processing | Leave a comment

7. Various bits


Constants look almost exactly like variables, but you can’t modify their content. With the keyword final a variable will turn into a constant, after which you can’t reassing new values to it. It is perfectly ok to use the value, though:

final int MYNUMBER=10;
int a;

a=MYNUMBER; // We can do this
MYNUMBER=11; // But not this

It’s a matter of taste and style, but writing constant names in ALL CAPS makes it immediately evident that they are not variables. But why do we need these constants? Some examples are fixed values that should never change, like PI. Another typical use is to replace numbers, such as screen coordinates or array sizes with a descriptively named constant that can be reassigned as needed in one go, instead of touching the code everywhere.

Building a little toolbox

Let’s put functions into good use again and build a couple of useful functions that will probably come in handy for your assignment, too. toolbox.pde

Circular and oscillating motion

Time to go back to your high school math and use sin/cos for drawing circles, ellipses and spirals. cos(angle) gives the x coordinate for a circle and sin(angle) the y coordinate. A couple of things to note: a full circle is 2*PI – Processing uses radians instead of angles. Another quirk is that, unlike with mathematical coordinates, the y axis points down, not up. circularmotion.pde

Posted in Processing | Leave a comment

6. Types and conversions

Let’s start with a nice little trick: instead of running your sketch, present it to make it fullscreen (shift-command-r).

Decimal numbers (desimaaliluvut)

So far we’ve used only int type for our calculations. Often the precision is not enough: for example if you divide one by two you get zero instead of 0.5. For more precision we can employ floating point numbers (liukuluvut), which can store decimal numbers. Instead of int, declare your variable float:

float mynumber;

An example illustrating the difference between the two: intvsfloat.pde

Type conversion (tyyppimuunnos)

Processing is very strict about mixing variables and functions of different types. You can’t directly assign a variable of float into an int. For example random numbers in Processing are floats, and that’s why you can’t assign them to int variables without conversion. Fortunately, type conversion is easy to do:

int a=0;
float b;

A few more conversions here: typeconversion.pde

One type more

Often it’s handy to have variables that contain yes/no values. For them we have type boolean, which can only have values true or false. You can’t do any mathematical calculations with booleans.

boolean truth=true;

Displaying text

We’ve output text with println already, but to display text inside the sketch window we need to use PFont together with loadFont, textFont and text. Processing has its own bitmap font format. Save your sketch first and then click Tools – Create Font. How to do all of it: graphicaltext.pde. A bit more advanced: graphicalnumbers.pde

Sample project

Finally, let’s make a complete program that puts everything we’ve learned so far into use. First, we start by thinking of the needs and requirements, then proceed to designing the overall structure of the sketch, and only after that we start typing anything — do the same with your exercise task! paintprogram.pde

Posted in Processing | Leave a comment

5. Functions, keyboard, images

Functions (Funktiot)

Also known as procedures or subroutines (aliohjelma) in many languages. They are a way to structure your programs to meaningful wholes for the sake of readability, and to avoid unnecessary copypasting of the same code over and over (you can also break your sketch to multiple files and have functions there separately). Like variables, functions too have a name, type and a scope. In addition to that they may have a return value and parameters. We’ve already defined two functions, setup and draw. We can create other functions exactly the same way:

void myfunc()
  println("Here we go!");

The function can be called by giving its name and parenthesis: myfunc(); This is exactly what we’ve been doing when we write things like size(640,480); or smooth(); How to make a simple function: simplefunction.pde


Parameters are a way to pass information to functions. When defining a function the parameters go inside the parentheses: type and name. Inside the function they are visible as any variables.

void printsum(int a,int b)

A complete example with parameters: parameters.pde

Return value

When the type of a function is void, it doesn’t return anything back to the caller. In many cases we need to get something back, such as information about whether there was a problem. If we define a function with a type (e.g. int), we can return things from it with return. Return will also stop the function and jump back to the caller. See returnvalue.pde


Like with the mouse, the simplest way to read the keyboard is to check the global variable keyPressed. If it’s true, key will contain the pressed key. It can be either a character in single quotes or a special value such as ENTER or BACKSPACE. However, when you get serious about it, both the mouse and keyboard are better supported using event handlers such as mouseClicked. A simple keyboard example: keyboard.pde. An advanced example of the use of event handlers: eventhandlers.pde


PImages let us load and display bitmap images (jpg/png/gif/tga). You can add images to your sketch through Sketch – Add File. You can also download them directly from URLs, but then they obviously won’t work, if you don’t have an Internet connection. Example images for today: player.jpg and football.png. How to load images and display them on screen: images.pde

Posted in Processing | Leave a comment

4. Arrays, loops, types, random

Arrays (taulukot)

So far we’ve used variables, which let you store single values and work with them. Often we need to process large amounts of data, and single variables aren’t enough for that. Arrays let you store multiple values of similar type. Like variables, arrays too have: a name, a type, value(s), and a scope. In addition to that they have size, which is the amount of member in the array. So, if a variable is a box, an array would be a pile of those boxes.

An array can be declared the following way:

int ourstuff[] = {2,4,6,7,8};

After this line ourstuff is at our disposal and contains five numbers. It’s possible to create arrays also without assigning any values, only specifying their size. An array with 100 members:

int ourstuff[] = new int[100];

Array members (also known as items) can be used exactly like variables, through referencing (viittaus):

ellipse(ourstuff[1],ourstuff[2], 10,10);

The number inside the brackets is known as index. The first index in C-like languages such as Java and Processing is zero. So, for ourstuff the indices are in the range 0..4

Arrays and loops

In general, arrays go together with loops, especially for loops. With a loop you can walk through all the members of the array when needed. The loop counter is used as the index. Two examples: arrayloop.pde and circlesfromarrays.pde

Often we don’t know the size of the array beforehand, or its size might change. A safe way to go through all the items is to use the length property that all arrays have:

for(i=0; i<ourstuff.length; i++)

Strings (merkkijonot)

A new type coming up. Type int lets us use integer numbers, but there’s many situations when other types are needed. Textual information can be stored in type String. You declare a string as any other variable.

String mytext;

Assignment is the same. A string is enclosed in double quotes:

mytext="Never gonna give you up";

You can’t directly assign variables of one type to another type. You need type conversion.

Debugging exercise

Download the following sketch: mousefollowbuggy.pde and fix it! There are ten errors altogether: some of them just minor typos and some more conceptual problems. Here’s the fixed one: mousefollowfixed.pde

Random numbers (satunnaisluvut)

Random numbers are essential for many purposes, for example games where enemies appear at random positions at random intervals. They can be generated using the random function. A random number from 0 to 100 (excluding number 100) is generated by random(100):

line(random(100),random(100), random(100),random(100));

A larger example

Let’s combine most of the things we’ve learned so far. A sketch that draws squares that can be removed with a mouse click: clicktokill.pde

Posted in Processing | Leave a comment

3. Flow control

Flow control

In numerous cases we need to do things conditionally, a number of times, or until something happens. For those sort of purposes we have different flow control statements:

  • if – do something if a condition is true
  • if-else – do something if a condition is true, otherwise do something else. See ifelse.pde
  • for – repeat something a certain number of times. Consists of the initial counter value, condition and increment. See forloop.pde
  • while – repeat something as long as a condition is true. Quite rare in Processing because of the way interactive sketches work, but common in other languages and environments.

These statements start a compound statement, which is a block of code enclosed in braces. Anything you put in there will be run or repeated, according to the statements above. You can also nest the compound statements, placing them inside each other. Nesting example: nestedloops.pde

Comparison operators (vertailuoperaattorit)

All of the above need conditionals. Comparison operators are used for comparing two things, such as numbers or variables. Some of the most common ones we’ll use in the future are:

  • Equal: == (very easy to mix up with assignment, beware!)
  • Not equal: !=
  • Greater than: >
  • Less than: <

Grouping conditionals

Conditionals can be grouped, if you want to do more comparisons in the same time:

  • And: &&
  • Or: ||

For example: if(mouseX>100 && mouseX<200). A complete example: exitbutton.pde

Indentation (sisennys)

It’s a good common practice to indent the contents of compound statements a few characters to the right, so that they are visually aligned. This way you can instantly spot the statements that are on the same level. Processing will do most of it for you automatically, but if your code has gotten ugly, you can clean it up by selecting it and then clicking Tools – Auto Format.

One more nitty detail: to quit your sketch use command exit()

Posted in Processing | Leave a comment

2. Variables (2), math, interaction

Recap of variables. Properties, declaration, assignment. Conflict with reserved words.

Simple mathematics in Processing

We can use variables for many kinds of calculations, such as addition (+), division (/), subtraction (-) and multiplication (*). In the mathematical statements we can use variables as well as numbers:


Optionally you can insert spaces to make it a bit more readable:

a = b/3 + a*3 -40 + c*b;

To see the number (will appear in the black box of the processing window) use print or println: println(a);

I’d rather not talk about these for now, but in a lot of tutorials and examples you will find things like this:


They’re only shorthand for a=a+1; and b=b-1; Use them only when you need to increment or decrement a variable by one, not in mathematic statements.

Interactive software

So far we’ve only made small sketches that are run once. For most uses we need to have the sketch running continuously. For this we need two things: setup (run once when the sketch starts) and draw (runs all the time). Things that you need once, like opening the window go under setup, things that are done continuously go under draw. This is a bit different to many other environments. An example program with setup and draw: setupdraw.pde

Comments (kommentit)

For the sake of clarity it’s essential to use comments. They serve both you and others reading your code. Comments are free-form and start with two slashes: // The rest of the line is ignored. Edit – Comment/Uncomment will do it automatically for you. Another use for comments is disabling a piece of code for testing purposes. comments.pde

Using the mouse

There are global variables named mouseX, mouseY, mousePressed and mouseButton, which you can use for simple interaction. Their values are updated automatically and they don’t need to be declared (they’re declared somewhere else). Their values can be used normally:

ellipse(mouseX, mouseY, 100,100);

An example doing something almost useful with a mouse: mousepaint.pde

Variable scope (näkyvyys)

Global variables, Local variables. Global variables are visible to all parts of the sketch. As a rule of thumb: the scope is the block enclosed in braces { }. Declaration must be done before use, too. Why are global variables bad? Different variable scopes in this example: variablescopes.pde

Posted in Processing | Leave a comment