This is an abstract from the book, "Start Programming with JavaScript" by Bill Tait. It is available in Kindle and paperback formats from the Amazon book store.
JavaScript. is a programming language that allows you to add functionality to a web page and turn it into a web application. It is not the same language as Java, but it does have a similar syntax to Java, and to C, C++, C# and Flash Actionscript. However, unlike these languages, it is interpreted by the browser rather than executed as machine code by an operating system. This means it is easier to learn and completely free. On the other hand the scripts are openly visible in the browser window as source code. So they cannot be protected from copyright infringement.
You don’t need any special software to write JavaScript. You can do that in the same text editor you use to write HTML and CSS documents. You can also test it in a browser so the development procedure remains the same.
A JavaScript program is embedded in a web page. In effect, the page is its user interface. However, it is unusual as a programming language in that it may be distributed in separate scripts throughout the HTML document. These are executed as and when they are parsed by the browser as it moves down through the page and they have access to all the HTML tags and text nodes.
The only exception to this execution process is that some scripts are not immediately executable. These include scripts known as functions and event handlers that simply load and await user interaction before they do anything.
There is an important difference between the HTML environment and JavaScript that is worth noting at this stage. HTML is case insensitive, so its keywords, in the form of tags, can be written in either or mixed case. Here, we will use lower case. JavaScript on the other hand is case sensitive. All its keywords are lower case.
One way to embed JavaScript is in the body of the document inside <script></script> tags. Such scripts, which are often quite small, are executed or, if they are not directly executable, stored, as soon as the browser parses the tag. So they are processed in the order in which they appear in the document.
An example of an embedded script is
<script>
var count = count+1;
</script>
An example of a script that is not immediately executed is the JavaScript URL. This is embedded in a hypertext link with a JavsScript code replacing the usual URL. The code is executed only when the link is clicked by the user, for example in the following script:-
<a href=”javascript:count=count+1;”>Increase count</a>
Other scripts that define stored functions are more often embedded in the head of the document which downloads before the body so that the scripts are available for use by other scripts in the body. These scripts are again contained within <script></script> tags but these may contain the actual code or a reference to an external file that is to be loaded.
In the first case an example might be as follows:-
<script>
function getName(){
username = prompt("Please enter your name","")
}
</script>
In the second case a file, myscript.js, can be loaded into the script with
<script src=”myscript.js”></script>
Here the file myscript.js is stored in the same folder, since there is no path specified, and it must be a pure text file, like the HTML and CSS files. And it requires no containing <script> tags.
As an illustration, here is a page that has examples of all four approaches. There is no need to understand any of the code except to be able to identify the four JavaScript inserts.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript Starter</title>
<script src="myscript.js"></script>
<script>
function getName(){
username = prompt("Please enter your name","")
}
</script>
</head>
<body>
<p>First we run the getName() function</p>
<script>getName()</script>
<p>Here is a JavaScript URL to check the input</p>
<p><a href="javascript:alert('Hi ' + username)">Check your name again</a></p>
</body>
</html>
A program comprises a series of commands to the operating system or, for JavaScript, to the browser. These commands are also known as instructions and, in high level, user friendly languages, as statements. A statement uses expressions made up of variables and operators to describe the instruction. It is here, in the statements, that we do our actual JavaScript programming.
Sometimes a statement will make use of, or call, a function which is code stored somewhere else in the program or in the browser to carry out some complex function that can be represented in the statement by a single function name. To convert a string value to a number, for example, a statement my use parseInt(word) which will call the parseInt() function and replace it in the statement with the numeric equivalent of the value represented by the variable, word.
So a JavaScript program (or any of its component scripts or functions) is comprised of a set of statements. Each may contain expressions, variables, operators and function calls.
An expression is just a formula that converts to some value. An operator is something that produces an effect on one or more variables. In the following example, “Hello “ is a string constant and yourName is a variable. The two are related by a + operator which has the effect of concatenating them into a single string.
“Hello “ + yourName
If we now add another operator, the assignment operator, =, and another variable, called message, we can have a complete statement that actually does something, as follows:-
message = “Hello “ + yourName;
This statement assigns the value of the expression on the right to the variable on the left and is called an assignment statement.
A mathematical assignment statement is similar to a mathematical formula. For example,
total = x + y + z;
And as an example of a function call, we might have
number = parseFloat(userInput) * 100;
This converts a user input to a floating point number, multiples it by 100 then assigns the value of this expression to the variable number.
An assignment statement uses an = operator to assign the value of some expression to a variable. We usually say “equals” but it does not mean “is equal to”. We have another operator for that. It means “is to be assigned a value equal to”. For example,
label.x = 20; label.x is assigned the value 20, its x-coordinate.
label.y = 30; label.y is assigned the value 30, its y-coordinate.
label.text = “Next”; label.text is assigned the string value “Next”.
or, reusing an earlier example,
String(text) = 5 + (13 – 3) * 3 / 2
which would evaluate the mathematical expression on the right, and assign the result to the string value of a variable, text, after casting it as a String variable.
An important result of this interpretation of assignment is that it can involve a variable being assigned to itself. For example, the assignment,
x = x;
is quite acceptable and would compile all right – although it would not have any effect. It would just assign the value of x to its current value. However, the statement
x = x + 1;
would certainly have an effect and it is very widely used in programming to increment the value of a variable. It means that the value of x should be assigned its current value plus 1.
Now we can look at some of these concepts in more detail.
A variable is an entity that represents a piece of data in a program. It is so called because its value may change during the execution of a program. Like the variables used in mathematics, it is usually a symbol, often a character or word, that represents some value. It is a placeholder for data to be supplied to the program or, in the maths case, the formula.
For example a, b and c may be variables that represent three numbers stored by the program. Their values may be input by a user or obtained by calculation and they may change during program execution. Without variables, there would be no way to write a program that can be used with any user or other input. Variables are what make programs programmable in advance of their use. Without them, data would have to be stored entirely in the program, such as in an ebook.
As you might expect, all variables must have unique names, or identifiers, that provide a means of identifying them. For example, x might be a variable representing the x position of some object and y its y position. As another example, a program variable, yourName might be used to get the name of the user then the rest of the program can use the value of yourName without knowing what it might turn out to be at runtime. It should work for all values of yourName, even unexpected ones. Testing a program usually involves trying outlandish values of input to variables to see how the program behaves.
Unlike HTML, JavaScript is case sensitive. So variable such as yourname and yourName are quite different variables. Keywords in JavaScript are always lower case.
Other than these rules, naming variable is quite straightforward. It is wise not to start with anything other than a letter, since some characters will cause trouble and you should avoid using any of the JavaScript keywords (which you have yet to learn). These are reserved for the language and include var if, else, while and a few others.
It is good practice to declare a variable before it is required in a program, usually somewhere near the beginning of the program. This ensures that all the variable names are collected together and helps to avoid duplication and name collision. They are usually declared with the var keyword. This means that variables declared inside functions are only visible in these functions and further helps to avoid collisions with variables declared in other functions. Without the var keyword they are global variables and visible everywhere.
JavaScript is sometimes described as loosely typed. It does have types of variables but this is not specified when a variable is declared as it is in other languages. A particular variable name may be used to describe any type of variable and this may change during execution.
There are four built-in types, apart from objects, as follows:-
Number any kind of number – floating point decimal or integer
String a string of text characters, or a single character
Boolean a Boolean value of true or false
Array an array of other variables
They are declared, for example, as follows:-
var num; to declare a variable named num probably to hold a Number value.
var word; to declare a variable named word probably to hold a String value.
Variables, at some stage in a program, have to be given values. If this is done when they are declared, it is described as initialization. It is a good idea to initialize variable since they may be used in a program before they have been given values and produce unpredicted results. For example we might have,
var num = 45;
var word = “next”;
Note the use of semicolons to terminate each of these declarations and initializations.
Note also that the value of a string is always stated inside quotation marks. These can be double quotes, as above, or single quotes. And, of course, we can have strings that look like numbers, such as “2011”. These are typically used for telephone numbers and addresses that are not going to be processed as numbers.
And one other oddity needs to be mentioned. We can have String values with nothing between the quotes, for example “”. This is called a null string and is used to make sure memory space is allocated without giving the string a value.
The attributes of HTML tags also behave like variables. The tags themselves can be regarded as objects of the tag type, their id values are their names and all other attributes are their properties represented by variables which are the attribute names. For example the following code declares an object of type img, with a name of slide1 and an attribute called src which specifies its location as well as width and height variables..
<img id=”slide1” src=”slide1.jpg” width=”200” height=”150”>
So the whole page is an application with objects and variables that can be used by any embedded scripts.
Comments can be added to JavaScript code in the same way that they are added to MXML code, but the syntax is different. In JavaScript, a double forward slash // means that everything on the following line is a comment and is to be ignored by the compiler. If we need longer comments then everything enclosed between a /* and a */ symbol is to be regarded as a comment, for example,
//This is a comment
/* This is a comment */
There are many operators in JavaScript but only the unary operator and the arithmetic operators are introduced here.
The only unary operator required here is the minus sign, -, which converts the value of a number to its negative equivalent. So -5 would have the usual value.
Arithmetic operators are the familiar set of * (multiply by), / (divide by), + (add), - (subtract) and brackets, ( and ). These are used exactly as they are used in mathematical expressions evaluating them in the order of bracket contents first, * and / next (from the left if there is any ambiguity, then the + and – operators (again from the left, if necessary). This is described as operator precedence. So, for example the following arithmetic expression evaluates to 20.
5 + (13 - 3) * 3 / 2 = 5 + 10 * 3 / 2 = 5 + 30 /2 = 5 + 15 = 20
Note that the * operator is never omitted next to brackets as it is in mathematics. For example, we must write 7*(6–2) rather than 7(6-2).
There are rules of precedence for all operators – not just the arithmetic ones.
A function represents a short piece of code that can be executed from anywhere in the program that is within its scope. It has a name, which must be unique (at least in a function within which it is defined) and conventionally starts with a lower case character and is followed by parentheses. These may contain information in the form of arguments that are to be processed by the function.
A function is executed simply by stating its name and any argument values in the form of variables or constant values. This causes the program to jump to the definition of the function and execute it using the arguments as input parameters. So it is a useful structure to hold code that is used more than once in a program.
The function may just do something or it may return a single value to the point where it was called so that it can then be used for some purpose.
For example, the parseFloat() function is a built-in JavaScript function. It takes a string argument and returns a numeric equivalent, if possible. So the code
pi = parseFloat(“3.14”);
would return a value of 3.14 and assign it to the variable pi.
A large number of functions are provided with JavaScript and the essence of good programming is to reuse these whenever possible. However, it is often necessary to define new functions. This is done for two reasons. One is to separate out scripts that are reused in several places in the document code thereby not having to repeat the code multiple times. The other is to make the main code more readable by abstracting out process with high level function names that are indicative of their purpose.
A function is declared with the function keyword and a unique name. It may also contain one or more parameters in parentheses. Then it is followed by a block of code in braces, which is the body of the function that is to be executed. This may include a return statement if the function is to return a value. For example, a function to
function name (parameters){
statements
}
The scope of functions is the same as for variables but without the var keyword. Functions declared in the body of the document are global while those declared inside another function are local to that function and not visible outside it.
The parameters are the names of any variables that are to be used inside the function to hold values passed as arguments from the main program. This is a subtle concept. Data sent to a function is described as arguments and represented by variables used in the calling program. These values are transferred to new parameters declared in the parentheses of the function and local to the function. They can, and usually do have different names from the arguments but if the same names are used, they are actually different variables, which can be confusing.
A function does not have to return a value but if it does it can be used by the calling program.. Only a single value can be returned and this uses the keyword, return, for example, return result.
An example of a function definition to add two numbers and return the result as a number might be of the form
function addNumbers(firstNumber, secondNumber){
var sum = firstNumber + secondNumber;
return sum;
}
This function addNumbers takes two arguments declared in the parentheses as parameters, or local variables, firstNumber and secondNumber. In effect, these are local variables declared in the function and they will be initialized to whatever values are passed to the function as its arguments. Then the function executes its statements, which define what the function is to do, which, in this case, is just to assign the value of the expression firstNumber + secondNumber, to a new local variable, sum.
This function can be called from some other script, with the code
total = addNumbers( n1, n2);
where the variables total, n1 and n2 should have already been declared and their current values are transferred to firstNumber and secondNumber which are known only to the addNumber function. Then the variable total is assigned the value returned by addNumbers.
A program is seldom just a linear series of statements. It almost always includes other structures. There are only two of these but they can be combined in such a variety of ways that the final configuration may seriously test your logic. One structure is called a decision and the other is called a loop .
Decisions are points in a program where the flow of execution can go along one of two or more paths. It is sometimes called branching because the program branches at that point or it may be called selection, since the program selects which branch to take. The decision always depends on the current state of some variable and if it meets some condition.
In fact, the most common decision structure is the "if" statement. This is a compound statement starting with the keyword if (remembering that keywords are case sensitive and they are all lower case), following up with a conditional expression in brackets and completing with a block of code in braces (or curly brackets), { and }. So it looks like this –
if (condition) {code statements}
Each of the code statements inside the block ends with a semicolon but the whole block does not. For example, to respond to user input we might have
if ( answer == “yes”) {
result = “correct”;
score = score + 1;
}
Here, the program arriving at this compound statement evaluates the condition and if it is true, that is, the current value of the variable, answer, is equal to the String “yes”, then it executes the code inside the braces. It changes the value of result to “correct” and increments the value of score, presumably to add to the user’s score. Otherwise it ignores this block and just goes on to the next program statement.
Note the use of the == operator. It is not a misprint. It is used to test if two values are equal since the other operator, =, is already used for assignment. One of the most common syntax errors occurs when = is used instead of ==. It is hard to spot since the program just assigns the value instead of comparing it and continues on its way to an incorrect outcome.
This example also illustrates the way we usually layout the code for these compound statements. The opening brace { is placed after the if and the condition, then comes the JavaScript code, sometimes indented to be clearly identified as a block, then comes the closing brace, } lined up with the opening if keyword. This makes it easier to scan through lots of code and spot missing or extra braces. In a program with many such structures this is a common error. This is compatible with similar indentation used in the HTML code to facilitate readability and will be used throughout the book except where the short line length and page breaks require alternative strategies.
There are alternatives to this location of the braces. Some programmers put the opening brace on the next line and line that up with the closing brace, for example as
if ( answer == “yes”)
{
result = “correct”;
score = score+1;
}
There is a variation on the if statement in the form of an if else statement. This has the following structure –
if (condition) {code statements)
else {code statements}
In this case, if the condition is evaluated and found to be true the first block of code is executed, otherwise the second block of code is executed. There is no straight through path this time. For example –
if ( answer == “yes”) {
result = “correct”;
score = score+1;
}
else {
result = “incorrect”;
}
And, there is a third version in which these if and else statements can be chained, with else if combinations and further conditions, for example –
if ( signal == “stop” ) {
lightColour = 0xff0000;
}
else if ( signal ==”ready”) {
lightColour = 0xffff00;
}
else if ( signal == “go” ) {
lightColour = 0x00ffff;
}
else { lightColour = #000000 }
This structure is better than a series of simple if statements to test each condition in turn since this would test all of them even if the first one turned out to be true. The else if only goes on to the next statement if the previous one fails. And note also that these single statements do not really need the terminating semicolons but they are included for consistency – another way to avoid errors.
A loop repeats a number of program statements for a certain number of iterations. It represents a way of writing a few lines of code and having them run many times. It is useful for repetitive tasks that otherwise might require an enormous number of statements.
In the "for" loop the number of iterations is known beforehand at the programming stage and prescribed in the statement. Typically, it is used to process a fixed number of data values.
It has the following structure:-
for (var index = 0; index < 100; index++) {
statements
}
As for the decision structure, this one starts with a conditional expression in parentheses but this is a rather complicated one comprising three linked terms separated by semicolons. This is again followed by a block of code that has to be executed. Again the execution is related to the conditions but this time the program loops back after each execution and tests the conditions again. This is repeated until the conditions give a false return. So the block of code is repeated a number of times.
The first term inside the brackets, var index = 0, is actually a declaration and initialization of a new variable. The variable could have been declared outside the for structure, or used previously, in which case the var keyword would not be required and it would be a simple assignment.
The second term, index < 100, defines the limit if the iterations. In this case while the value of index is less than 100. As soon as it hits 100 the cycle stops.
The third term describes how the value of index is to change from one iteration to the next. In this case it is to be incremented by 1.
This example instructs the program to give index a starting value of 0 then increment it by one until its value equals 100. For values 0 to 99 the block of code will be executed.
Here is another example. This one decrements an index variable, this time called n. It calculates the factorial of a number. That is, number * ( number-1) * ( number-2) and so on down o *1. It is used in calculations of probability, for example.
var number;
number = prompt(“Enter a umber”,””);
for (n=number; n>1; n--) {
number *= n - 1;
}
result = number;
The value of number is multiplied by one less than its current value until that is at least 1 and the result is the factorial of the number. Note that the loop does not allow number to reach a zero value which would make the result zero.
The alternative to the for loop is the while loop. It does not prescribe the number of iterations since this is not known until the program is actually running. This time, a block of statements will be repeated as long as some condition remains true usually in response to some user input. The structure is again that of a condition in parentheses followed by the block of code to be repeated:-
while ( condition ) {
statements
}
An example of this structure is as follows:-
while (answer == “yes”) {
playGame();
}
This repeatedly asks the user if they want to play the game again. If the answer is “yes” it calls a game function, playGame(). Otherwise, it exits the loop. When the playGame() function ends the program goes back to the while condition and asks the user again.
Of course, it is quite likely that the user will enter “YES” or “Yes” instead of the “yes” specified in the conditional test so we might want to apply our knowledge of logical operators and change the condition to
while ( answer == “yes” || answer == “YES” || answer == “Yes”)
The logic may be a little hard to follow here and some programmers might make the mistake of using && operators instead of ||. What you want is a true outcome of any one of these conditions.
And just for fun, we can rewrite the previous factorial calculation as a while loop instead of a for loop. Without further explanation, the code is as follows:-
var number;
var n = number;
while (n >1){
number *= n - 1;
n--;
}
result = number;
Finally another loop point to note is that there is a danger with while loops and, to a lesser extent, for loops in that the conditions can be incorrectly stated so that they never become false. In this case the loop will go on repeating forever and the program will “hang”. Infinite loops have to be guarded against. And the opposite can happen where careless programming results in a condition that can never be true, so the loop will never be entered.
A computer system continuously monitors all of its input devices, including the mouse, keyboard and even the internal clock and file system, for any input. When this occurs it interrupts what it is doing and sends an appropriate message to the operating system which, in turn, passes on the information to any running software. Here it is treated as an event and associated with the software object on which the event took place.
The event has a specific name, which can be used by the programmer to handle the event. It is detected at an object, which is often a user interface element that is programmed to respond to events. The object has an event listener attached either by the browser or by the programmer. The same object then dispatches a message to a named function which the programmer designates as the event handler. So as far as the software designer is concerned an event is generated at an event listener and has a specific name and event handler function.
Some events are included in the browser API and have built-in listener objects and handlers. For example, a mouse click on a hyperlink executes a built-in browser function to download a web page and a form may have a button that listens for clicks and usually responds by submitting the form to a server program. It is up to the programmer to decide what should happen next. In this case the event is called a click event and the handler is called “onclick”. This is really a function but is specified as a property of the button object, that is, as an attribute without the usual parentheses. For example, we might have
<input type = “button” onclick=”showTime()”>
The programmer may also use style sheets or JavaScript to create new targets by adding event listeners to otherwise inert elements, such as <div> elements then specify what handler is to be invoked. This allows style sheets and JavaScript to add considerable interactivity to a web page.
In desktop and laptop systems, mouse events are the most common user generated events. In mobile systems these are replaced by touch and gesture events but mobile browsers will interpret most mouse events as gestures. The only exception is the event dispatched when a mouse hovers over a hyperlink or other element, where there is no touch equivalent. In fact, touch events have to be specifically programmed for web applications that are to be converted to native mobile apps or for the gestures for which there is no mouse equivalent.
When a user clicks the mouse on an object that has an “onclick” attribute it dispatches a click event that can be handled by the code defined in the attribute value. Since it is defined in HTML, the name is case insensitive and often written as “onClick”. The JavaScript code can be written in the attribute or, if it involves more complex processing, in another handler function that is called from the attribute.
The main mouse events, with their handler attributes are
For example, to handle a click event on a button element the code might be inserted in the onclick attribute, as
<input type=”button” value=”=” onclick=”alert(‘Hello, there’)”;>
Note the use of single quotes inside the outer ones to concatenate the output and, as usual, the semicolon is only really necessary to separate multiple statements.
Alternatively, the onclick attribute may call a more complicated function defined elsewhere,
<input type=”button” value=”=” onclick=”greetUser()”>
You can do the same thing with a script, for example,
<script>
var butn = document.getElementById(“greeter”);
butn.onclick = greetUser();
</script>
The event is often associated with an event object which has a number of useful properties that can be accessed by the handler. For example, the mouse click event delivers the x and y positions at which the click occurred. To illustrate this we can get its x and y positions in the browser window, clientX and clientY and do something with them.
One of the bad features of JavaScript programs is that they are often distributed in separate scripts throughout the HTML. This mixing of functionality and user interface is an error prone arrangement and one that limits the functionality to event targets provided by the browser. It is much safer and more useful to separate the functionality from the user interface and work with a single application code, as is done in other application programming languages.
We could do this by simply putting all our program code in the head of the document where it is separated from the user interface body but this runs the risk of program execution starting before the user interface has loaded. So an alternative strategy is to use an “onload” attribute in the body element which calls an event handler to run only when the body has loaded and the user interface is fully in place.
The main events associated with file loading are
Load onload Page or other element has completely loaded into the browser
Unload onunload Page is about to be replaced or browser closed
If the onload handler is placed in the body of the page it triggers the application script when the page has loaded. It can also be added to another loaded element, such as an image tag to execute code when the image has loaded.
The same is true of the onunload handler which executes when a page or some other element is unloaded. This happens when another page is downloaded into the browser to replace the scripted one. It can do some tidying up before that happens. For example, it can save a bookmark in an ebook.
The downside of this approach is that we now have to assign event listeners and handlers to the interface elements programmatically.
The Canvas element is a rectangular drawing area added to the HTML. For example, a 200 by 200 pixel canvas might be specified as
<canvas id="canvas1" width="200" height="200" style=”background-color:#ddd;”></canvas>
In this case it is also styled with a gray background color just to make it visible.
The actual drawing is done with JavaScript. For example to draw a red square on the example canvas, we might have
<script>
function drawSquare(){
var canvas=document.getElementById("canvas1");
var context=canvas.getContext("2d");
context.fillStyle="#f00";
context.fillRect(20,30,80,100);
}
</script>
This illustrates the general procedure for drawing a shape on the canvas. A variable is obtained for the canvas and this is used to get a drawing context which in this example is called “context”. Then a series of context methods are used to create a shape, or even a set of shapes, and display the result on the canvas.
The context includes the default drawing styles and the coordinate system in which the drawing takes place. The only context available at present is the “2d” context so it is a routine process. The context has a large number of properties and methods of which a working set will be introduced here.
In this example the fillStyle property is set to a red color so that all subsequent drawing will be in red. Then it draws a rectangle at the coordinates 20, 30 80, 100, where 20, 30 are the x and y coordinates of the top left corner of the rectangle and 80, 100 are the x and y coordinates of its bottom right corner. The default origin of the 2d context is at the top left corner of the canvas so the rectangle is 20 pixels in from the left and 30 pixels down from the top of the canvas as illustrated in Figure 1.
The full HTML code is as follows:-
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Canvas Graphics</title>
<script>
function drawSquare(){
var canvas=document.getElementById("canvas1");
var context=canvas.getContext("2d");
context.fillStyle="#f00";
context.fillRect(20,30,80,100);
}
</script>
</head>
<body onLoad="drawSquare()">
<canvas id="can" width="200" height="200"></canvas>
</body>
</html>
This uses the onload event to call the drawSquare() function.
In fact the rectangle is a special case, mainly because it is so common. Other shapes are drawn differently. For the rectangle, the methods include
context.fillStyle = “#f00” to set the fill color
context.strokeStyle= “#00f” to set the line colour
context.fillRect((x1, y1, x2, y2) to draw a filled rectangle on the canvas
context.strokeRect(x1, y1, x2, y2) to draw an outline rectangle
context.clearRect(x1, y1, x2, y2) to draw an empty rectangle
Before drawing a rectangle you can specify the fillStyle and strokeStyle properties of the context. Then use one of the drawing methods.
A range of different shapes can be drawn as a series of paths. Straight paths form a polygon and curved ones form arcs or complete circles. A new shape starts with a beginPath() method then uses moveTo() and lineTo() methods to draw the polygon sides and fill() to close it, fill it with the current fill style and draw it on the canvas. For example to draw a filled red polygon with a blue outline the sequence is of the form
context.fillStyle = “#f00”; set the fill to red
context.strokeStyle= “#00f”; set the stroke to blue
context.beginPath(); begins the drawing
context.moveTo(x1, y1); moves to point x1, y1 without drawing
context.lineTo(x2, y2); draws a line from x1, y1 to x2, y2
context.lineTo(x3, y3); draws a line from x2, y2 to x3, y3
context.lineTo(x4, y4); draws a line from x3, y3 to x4, y4
context.fill(); closes the shape and fills with the current fill colour.
Each shape must begin with beginPath() and end with close() or fill(). If the beginPath() is omitted all the shapes will be joined up. The fill() and close() methods automatically complete the shape by joining the last point to the starting location.
To draw a curve, the arc() method is used. This takes five parameters, the x and y coordinates of the center of the arc, the radius of curvature and the initial and final angles of the arc. For an arc centered at x, y, with radius, r, and angles a1 and a2, the code is
context.arc(x, y, r, a1, a2) to draw an arc from a1 to a2
The angles a1 and a2 must be expressed in radians. To convert degrees to radians the degree value is multiplied by Math.PI/180. So, for example, a complete circle can be drawn from 0 degrees to 360 degrees with the values 0 and 360*Math.PI/180, which reduces to Math.PI*2. The constant Math.PI is equal to 3.14159 so this can be hard coded into your application if preferred. Then a full circle would be an arc from 0 to 6.2832 radians.
By default, these angles are measured clockwise from a1 to a2 and the 0 angle is along the positive x-axis, that is, the right pointing axis.
To draw a full circle, the code might be
context.beginPath();
context.arc(100, 100, 50, 0, Math.Pi*2);
context.fillStyle=”f00”;
context.fill();
Note that there is a possible sixth parameter. This is a Boolean with the default value, false. Changing it to true measures the angle in an anticlockwise direction.
You can learn more about JavaScript programming in my book "Start Programming with JavaScript" published in Kindle and paperback format by Amazon.