Best JavaScript Book For Beginners
If your looking to learn JavaScript your in the right place. This is the best JavaScript book for beginners. It's freely available online with tons of great coding examples. We'll cover all the basics of JavaScript so you can get started writing your own interactive projects.
This course is for the beginner to intermediate coder or anyone that just wants a refresher on JavaScript Syntax. After reading this article you'll want to start creating your own JavaScript projects. This is the best way to learn how to code. Use a search engine to find things you don't know or when you get stuck. There are a lot of great resources out there. Ill include some in this book.
What is JavaScript? Why should I learn it?
JavaScript is one of the 3 languages all web developers must learn. HTML, CSS and JavaScript form the basis of front-end web development. HTML defines the content, CSS is used to design how that content looks and JavaScript is used to program the behavior of web pages.
JavaScript enables you to create interactive elements, dynamically updating content, control multimedia, animate elements, and modify the content of a page. It works on all modern browsers both on desktop and mobile.
A strong knowledge of JavaScript will allow you to create web applications and browser games.
How JavaScript Works?
JavaScript is a Client-side Scripting Language. This means it's a web programming language that works in the browser. JavaScript works by manipulating elements on the page with DOM (Document Object Model). It allows you to make changes to a web page after it has loaded to my it feel more dynamic. Every html element on the page can be access and changed with JavaScript.
Javascript Overview
JavaScript Fundamentals For Absolute BeginnersHow To Follow Along With This Java Script Course Online
Download a code editor to write JavaScript on your computer.
A code editor makes your code easier to read by highlighting the syntax in different colors. It can also help suggest and auto complete code while your typing to save time. Sometimes finding errors can be tricky. A code editor can help you do that too.
- Sublime Text
- Visual Studio Code
- Notepad ++
JavaScript Console
You can also test code by pasting it in the JavaScript Console. Errors & warnings will also appear in the console. If your code isn't working that's a great place to go to figure out why.
CHROME
To open the console in Chrome, you right-click on a web page and then click "Inspect," and them developers window will appear. Click the "Console" tab next to elements tab in that window. A quicker way is to use a keyboard shortcut.
MAC: Cmd + Option + J
WINDOWS: Cmd +Shift +J
JavaScript Basics PDF
Coming Soon - JavaScript Basics PDF download so you can read it from anywhere. No need for an internet connection. Ill include the entire JavaScript Tutorial as a pdf.
JavaScript Course Content Examples
Coming Soon - Download this package to get access to all the JavaScript course content and coding examples.
How do I add JavaScript to a webpage?
To insert JavaScript into a web page, use the <script> tag. The older method used the type or language attributes. This is no longer required as JavaScript is now the default scripting language inside the browser.
Option: 1 (Old Way)
<script language="javascript">
// Javascript code here
</script>
Option 2: (New Way / Shorthand)
<script>
// Javascript code here
</script>
Option 3: Load An External JavaScript File
<script type="text/javascript" src="script.js"> </script>
Display A Warning If Javascript Is Disabled
<noscript>
<p>Please Enable Javascript to View This Page Properly!</p>
</noscript>
How to add jQuery to website?
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<script>
$(document).ready(function(){
// JQuery code here
});
</script>
How to add jQuery to wordpress?
<script>
jQuery(document).ready(function($) {
// JQuery code here
})
</script>
How do I add JavaScript to a wordpress website?
To add JavaScript to a WordPress website with a plugin download and install the HFCM Plugin. Stands for Header Footer Code Manager. With this plugin you can add site wide or page specific JavaScript code to the header or footer of your wordpress website. It has a lot of handy features including one that will allow you to disable code from one place, use short codes, and add code to just the mobile or desktop versions of your website.
Storing & Manipulating Data With Variables
Variables are containers for storing data. A variable name is a label that points to this data that will allow you to access and manipulate this stored data. Creating a variable is called declaring it. You declare a variable in JavaScript by using the var keyword. Generally it’s best practice to declare all variables at the beginning of a script. All variables must be identified with a unique name. To assign a value to the variable, use the = sign. A variable declared without a value will have the value undefined. It’s best practice to end all lines of code in JavaScript with a ; semicolon. It’s not required but it’s considered best practice.
There are 3 ways to declare a variable in JavaScript.
- Var: Global Scope – Can be accessed from anywhere.
- Let: Local Scope – Only lets you use the variable within the block you declared it in. (Best practice to avoid naming collisions)
- Const: A variable that can not be changed.
The general rules for creating names for variables are:
- Variable names can contain letters, digits, underscores, or a dollar sign.
- Names must begin with a letter and not a number.
- Names can also begin with $ (but that’s usually reserved for JQuery)
- Names are case sensitive so (Price and price are different variables)
- Reserved keywords cannot be used as variable names.
- It’s best practice to use Camel Case for variable names. First letter of the first word is small. First letter of all following words should be capitalized.
JavaScript Provides 7 Different Data Types:
You can get the type of a variable using the typeof keyword: typeof variable;
- undefined: variable that hasn’t been defined.
- null: Means nothing. Set a variable to be nothing.
- boolean: Set a variable to true or false.
- number: Variable that contains any number.
- string: Variable that contains any text.
- symbol: A symbol may be used as an identifier for object properties and dynamically produces an anonymous, unique value.
- object: An object can store key value pairs.
Escape characters inside a sting.
Some chatacters don't work inside a sting and need to be escaped to work.
Quote | \’ |
Double Quote | \” |
Back Slash | \\ |
New Line | \n |
Carriage Return (Simular to new line) |
\r |
Tab | \t |
Backspace | \b |
Form Feed A form feed is a page-breaking. Forces the printer to start a new page. |
\f |
Bracket Notion
Get a character within a specific index of the string. Remember that javaScript uses ZERO BASED INDEXING which starts at 0 not 1.
Numbers & Variables In Javascript
In JavaScript, just like in algebra, we can use variables in an expression.
Javascript Arrays - Storing Data In Lists
Arrays are a way to store multiple values in one variable. They’re great for storing a list of items. Creating an array is similar to creating a variable except you assign it with square brackets with your list of items inside . Make sure to wrap string items in quotes "string".
Access The Elements Of An Array
You can access the values by referring to an index number in the array. Array indexes start with 0 so the first item will have an index of 0.
Nested Arrays [Multi Dimensional Arrays]
A nested or multidemensional array is an array inside of an array or an array of arrays.
Array Methods
toString() | Converts an array to a string with each value separated with a comma. |
join() | Joins an array into a string but allows you to specify your own separator. |
pop() | Removes the last value from an array. It can also return the last element in the array. |
push() | Adds a new element to the end of an array. It can also return the length of the new array. |
shift() | Removes the first element of the array. It can also return the value that was shifted out of the array. |
unshift() | Adds a new value to the beginning of an array. |
splice() | Add new elements to an array at a specified point. |
concat() | Creates a new array by joining 2 arrays together. |
slice() | Slices out a section of an array into a new array. It does not remove any values from the source array. Can take up to two arguments. A start and an end point. |
JavaScript Conditional Logic - If Statements
If statements are used to make decisions in code. If this happens then do this. If not, do this instead. The order matters once the first condition is met it does not check any other conditions.
Use the else if statement to specify a new condition if the first condition is false. Use the else statement to specify a block of code to be executed if all other conditions are false
Comparison Operators
== | Equal operator
= assigns |
=== | Strict equal operator
There is no variable type conversion. |
!= | NOT equal | !== | Strict NOT equal |
> | Greater than | < | Less than |
>= | Greater than or equal to | <= | Less than or equal to |
&& | AND operator
If (val <= 50 && val >=25) { |
|| | OR operator
If (val < 50 || val >20) { |
JavaScript Switch Statements
The switch statement allows you to perform different actions based on different conditions. It then runs a block of code based off of those conditions.
The default keyword specifies the code that will run if there is no match.
The Break Keyword stops the execution inside the switch block. Used to jump outside of the switch statement and not make any further checks. The last condition doesn’t need a break as that happens automatically.
Ternary Operator
The Ternary Operator ? Is a shortcut for If/Else Statements. Allows you to shorten the condition into one line. It will assign a value to a variable based on some condition. The downside is it can make the code harder to read.
JavaScript Functions
A function is a block of code that is designed to perform a task that can be used over and over again. Functions are very important in Javascript.
Create Your Own Functions
The Function Keyword: is used to define a function. It’s followed by its name and parentheses (). Function naming follows the same rules as variables. The code that gets executed when the function is called goes between the curly brackets {}.
Parameters: Are variables listed inside the parentheses as a part of the function definition. Parameters allow you to input data into the function to produce different results.
The Return Statement
Stops code from executing inside the function. It also returns a value to the function caller. Every function in JavaScript returns undefined unless otherwise specified. This function doubles its input then returns the value to the caller so that can be read inside the console.
JavaScript Arrow Functions
Arrow functions were introduced in ES6 as a new way for writing function expressions. With them you can accomplish the same result with fewer lines of code. Instead of the function keyword, it uses an arrow => made from an equal sign and a greater than symbol. You don’t need the return keyword or the {} if the function is a single line. Using arrow functions saves typing but in my opinion makes the code more difficult to read.
JavaScript Loops
Loops are used to repeatedly run a block of code over and over again until a condition has been reached. This is often the case when working with arrays. You would want to loop through all the data and perform some kind of action on them. JavaScript offers several ways to run loops.
In terms of best practices and conventions, for loops are for a known number of iterations and while loops are to be executed until their intended job is done.
For Loops
A for loop is made 3 important parts.
Initialization: The starting point of the counter.
Test Statement: Set the end point of the counter. Test to see if the counter has been reached. If it has exited the loop. If not run the code inside the loop until it does.
Iteration Statement: Amount to increase or decrease your counter by.
For Loop Syntax
for ([initialization]; [test condition]; [iteration statement]) {
// Statement(s) to be executed if test condition is true
}
For Loop - Examples
Count To 10
document.write("Count to 10.." + "<br />");
for(var count = 1; count <= 10; count++) {
document.write(count + " ");
}
Lets modify this a little to be a count down timer for a rocket ship.
Countdown Timer
document.write("Starting Countdown.." + "<br />");
for(var count = 10; count >= 1; count--) {
document.write(count + " ");
}
document.write("Blast Off!!!!!");
The most common use of a 'for loop' is to loop through an array.
Loop Through An Array
var fruitArray = ["Banana", "Apple", "Grape", "Orange", "Cherry"];
for (let i=0; i< fruitArray.length; i++) {
document.write(fruitArray[i] + "<br/>");
}
JavaScript While Loop
This one loops through a block of code as long as a specified condition is true.
While Loop Syntax Example
while (condition) {
// code block to be executed
}
While Loop Example
var c=0;
while (c < 25) {
console.log(c);
document.write(c+"<br>")
c++;
}
An infinite loop will keep running forever. If you accidentally make one you can crash your browser or computer. In the above code if you forget to increase the variable used in the condition, the loop will never end. A loop can be terminated with the break keyword.
Break Out of a Loop Example
// Set a condition to true
const iceCapsAreMelting = true;
let polarBearsLeft = 5;
// Initiate infinite loop
while (iceCapsAreMelting) {
console.log(`There are ${polarBearsLeft} polar bears.`);
document.write(`There are ${polarBearsLeft} polar bears.<br>`);
polarBearsLeft--;
// Terminate infinite loop when following condition is true
if (polarBearsLeft === 0) {
console.log("There are no polar bears left.");
document.write("There are no polar bears left.");
break;
}
}
Do…While Loop
Similar to the while loop except the block of code will run first, then the condition will be tested to see if it should run again.
Do While Loop Syntax Example
do {
// code block to be executed
} while (condition);
DOM - Document Object Model
What is DOM?
DOM or Document Object Model is an interface that allows programs and scripts to dynamically access and update the content of a website. It turns every element on the page into an object and allows you to access it with JavaScript or other languages. This is how you can change, add or delete HTML elements even after the page has loaded.
With DOM you can:
- Change the content of an HTML element.
- Change the styles or CSS of an HTML element.
- Add, delete, hide or perform actions on HTML elements.
- Change the value of properties.
DOM METHODS
The document object contains all objects on your page. Methods are actions you can do. on those objects. If you want to access an HTML element on the page you always start with the document object then a method.
document.getElementById() | Most common way to access an HTML element is with its ID. |
document.getElementsByTagName() | Access an element by tag name. |
document.getElementsByClassName() | Access an element by class name. |
document.querySelectorAll("p.intro"); | Finds all HTML elements that match a specified CSS selector |
document.createElement(element) | Creates a new HTML Element. |
document.removeChild(element) | Remove an existing HTML element. |
document.appendChild(element) | Adds an HTML element |
document.replaceChild(new, old) | Replaces an HTML Element |
DOM PROPERTIES
A property is a value you can set or get.
.innerHTML | Allows you to get or change the content of an HTML element. |
.attribute | Allows you to change an attribute of a HTML element. |
.style.property | Allows you to change the style of an HTML element. |
.setAttribute(attribute, value) | Allows you to change an attribute value of an HTML element. |
How To Change The Content Between HTML Tags With The DOM
Grabs the element by it's ID & adds HTML content inside that element.
document.getElementById("text_01").innerHTML = "<b>New Text!</b>";
Grabs the element by it's ID & adds TEXT content inside that element. NO HTML.
document.getElementById("text_01").textContent = "New Text!";
You can also store the element in a variable and perform actions on the variable.
var text = document.getElementById("text_01");
text.textContent = "New Text!";
Change The CSS Styles Of An Element
To change the style of an HTML element use .style followed by the .propertyName. The attribute names are similar to CSS just without the dash. Use camel case instead.
Changes the text color to blue.
document.getElementById("text_01").style.color = "blue";
Adds a 3px black border to the bottom of the element.
document.getElementById("main-header").style.borderBottom = 'solid 3px #000';
Change An Attribute Of An Element.
Changes the image.
document.getElementById("myImage").src = "sad.jpg";
Change Elements by Class Name.
var items = document.getElementsByClassName('list-group-item');
// Outputs the whole collection of items with this class name to the console.
console.log(items);
//Outputs the second list item to CONSOLE. Starts counting for 0.
console.log(items[1]);// Change text of the second list item,
items[1].textContent = "Changed Text In List";// To change something about all items with that class name you need to use a loop.
for (var i = 0; i < items.length; i++) {
items[i].style.backgroundColor = "#f4f4f4";
}
Change Elements By Tag Name.
// Finds all <p> tags and stores them in a variable
var pTags = document.getElementsByTagName("p");
// Change the background of all <li> elements
var li = document.getElementsByTagName("li");for (var i = 0; i < li.length; i++) {
li[i].style.backgroundColor = "#f4f4f4";
}
Change Elements With Query Selector.
Only grabs the first element in the list. You can use any CSS selector.
// Find all <p> tags with class name intro. Classes use a period as a selector.
var pTagsIntro = document.querySelectorAll("p.intro");//# Grabs the elements ID.
var header = document.querySelector('#main-header');
header.style.borderBottom = 'solid 4px #ccc';// Changes the value of the first input field.
var imput = document.querySelector('input');
input.value = "Hello World";// Changes the value of the first submit button.
var submit = document.querySelector('input[type="submit"]');
input.value = "SEND";// Changes the text color of the last list item
var lastItem = document.querySelector('.list-group-item:last-child');
lastItem.style.color = "blue";// Changes the text color of the 2nd list item
var secondItem = document.querySelector('.list-group-item:nth-child(2)');
secondItem.style.color = "blue";
Change Elements With Query Selector All.
Grabs all the elements and stores them in a list. .
// Selects the second <h2> tag and replaces the text
var titles = document.querySelectorAll('h2');
titles[1].textContent = "hello";// Change the background color of all odd & even list items
var odd = document.querySelectorAll("li:nth-child(odd)");
var even = document.querySelectorAll("li:nth-child(even)");
for(var i =0; i < odd.length; i++){
odd.style.backgroundColor = "#f4f4f4"; even.style.backgroundColor = "#ffffff";
}
TRAVERSING THE DOM
Moving up and down with your DOM selection. Looking at parent, sibling & child nodes etc.
THE PARENT NODE: <h1><b>Text</b></h1>
Element outside an HTML tag. The Parent of <b> is <h1>
var itemlist = document.querySelector('items');
//Send parent node to console
console.log(itemlist.parentNode;)//Change the style of a parent node
itemlist.parentNode.style.backgroundColor = '#f4f4f4';
//Move up several parents
console.log(itemlist.parentNode.parentNode.parentNode;)
//PARENT ELEMENT - Pretty much Does the same thing
var itemlist = document.querySelector('items');
console.log(itemlist.parentElement);
itemlist.parentElement.style.backgroundColor = '#f4f4f4';
//Move up several parents
console.log(itemlist.parentElement.parentElement.parentElement;)
CHILD NOTE: <h1><b>Text</b></h1>
The elements inside. <b> is a child of <h1>
// Gets the first child
console.log(itemlist.firstElementChild);
itemList.firstElementChild.textContent = 'Hello 1';// Gets the last child
console.log(itemlist.lastElementChild);
itemList.lastElementChild.textContent = 'Hello 5';
SIBLING NODE: <ul><li>Item 1</li><li>Item 2</li></ul>
Elements beside each other. Item 1 & 2 are sibblings of each other.
//NEXT SIBLING
console.log(itemList.nextElementSibling);
//PREV SIBBLING
console.log(itemList.previousElementSibling);
itemList.previousElementSibling.style.color = 'green';
CREATE , INSERT DOM ELEMENTS
// Create a div
var newDiv = document.createElement('div');
// Add a class name
newDiv.className = 'newDivClass';
// Add an ID
newDiv.id = 'div1';
// Add an attribute
newDiv.setAttribute('title', 'newDivClass');
// Create a text node
var newDivText = document.createTextNode('Hello Word!');
// Adds the text to the div
newDiv.appendChild(newDivText);
//Add inside the document inside before the <Header> element with container class
var container = document.querySelector('header .container');
var h1 = document.querySelector('header h1');
console.log("newDiv");
newDiv.style.fontSize = '30px';
container.insertBefore(newDiv,h1);
DELETE DOM ELEMENTS
JavaScript Events
An event is something the browser does or something the user does. JavaScript can react to events and then let you run code after the event has been detected. Since JavaScript code is usually several lines long It's more common to see events calling functions.
Examples of JavaScript Events:
|
Example 1: Example 2: |
ADDING AN EVENT HANDLER TO AN HTML ELEMENT (Old Way)
JAVASCRIPT EVENT HANDLERS (New Way)
This is the better way of handling events because it keeps HTML clean. The JS Events and HTML are Separated. No need to modify the HTML document to get an event to work.JAVASCRIPT EVENT PROPAGATION
This is the blanket term for both event bubbling and capturing. This refers to the order in which event handlers are called.1. EVENT BUBBLING (Default):
When capture = false Events ripple up from child element all the way to the top of the document. Starts with the element that triggered the event then moves up the DOM tree to the parents in the hierarchy. If this parameter is omitted the default value is false.2. EVENT CAPTURE:
When capture = true With event capture it run the function on the way down. Events go from top of the document (The window object) all the way down to the element that was clicked.Debugging
JavaScript Objects - OOP: Object Oriented Programming
Procedural Programming:
Procedural programming, also known as inline programming takes the top-down approach. Its basicly a list of instrctions for the computer to follow. It's a style of programming that uses variables to store data and functions to modify that data.
Usually simple & straight forward for small scripts but often ends in spaghetti code with large programs. This happens because there is an Inter dependency between functions. This can become problematic and break things in large programs.
OOP: Object Oriented Programming
EXAMPLES OF OBJECTS:
OBJECT: Car PROPERTIES: Model: "Tesla", Color: "Red", LicencePlateNo: "FG 4589", METHODS: stop(); start(); move(); changeGear(); | OBJECT: Local Storage POPERTIES: length: 0, METHODS: clear(); getItem(); removeItem(); SetItem(); | OBJECT: Person POPERTIES: firstName: "Nate", lastName: "Ergang", age: 30, METHODS: wakeUp(); eat(); sleep(); |
4 PILLARS OF OOP
1 ENCAPSULATION:
2 ABSTRACTION:
3 INHERITANCE:
4 POLYMORPHISM:
Creating Objects
Multiple Instances of Objects
2 Ways to create objects with functions. Use these if you plan to create multiple instances of the same object.JavaScript Local Storage
Local storage is the ability to store information locally in the browser. This allows you to save the visitors data even when the user refreashes or leaves the page. This is good to move data between pages on your site. Each domain willstore data separtly so you only have access to data from your domain. Depending on the device the local storage can hold anywhere from 2Mb - 100MB+ of data. Javascript objects are converted to a JSON string before being saved in the browser. You can use javascript to read, write and delete data from local storage. You can look at this information in the developer tools under resources >> local stoarge.
The localStorage object comes with these methods:
localStorage.setItem();
localStorage.getItem();
localStorage.removeItem();
Taking user input from a form & storing it in Local Storage
Let combine everything we've learned so far into a little project that takes user input and stores it into local storage. The user can choose to retrieve that data or delete it. Here's an example and the code that make it work.[javascript title="LOCAL STORAGE User input from a form "]</p> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Local Storage Example</title> </head> <body> <form id="ls-form"> Name: <input type="text" id="ls-name"><br> Message:<br> <textarea name="message" rows="10" cols="30" id="ls-message"> </textarea><br> <input type="submit" value="Send Data" id="ls-send"> <input type="submit" value="Retrieve Data" id="ls-retrieve"> <input type="submit" value="Delete Data" id="ls-delete"> </form> <br> <span id="ls-data"> <span> <script> //Variable declarations using document object model var lsForm = document.getElementById("ls-form"); var lsName = document.getElementById("ls-name"); var lsMessage = document.getElementById("ls-message"); var lsSend = document.getElementById("ls-send"); var lsRetrieve = document.getElementById("ls-retrieve"); var lsDelete = document.getElementById("ls-delete"); var lsData = document.getElementById("ls-data"); //Event Listeners lsForm.addEventListener('submit', submitForm); // Fires once you submit form lsSend.addEventListener("click", sendData); lsRetrieve.addEventListener("click", RetrieveData); lsDelete.addEventListener("click", DeleteData); //Stops the form from submitting and refeshing the page function submitForm(e) { e.preventDefault(); } //Send Data To Local Host function sendData() { console.log("Sending data to local host...."); //Takes the data from the form and stores it in an object. x = {"name": lsName.value, "message": lsMessage.value}; // Converts the object into JSON and adds it to the local storage object. localStorage.setItem('siteData', JSON.stringify(x)); } function RetrieveData() { //Checks to see if local storage exists if (localStorage.getItem('siteData') != null){ console.log("Retrieveing data from local host...."); // Converts the data back into an object localData = JSON.parse( localStorage.getItem('siteData') ); // Converts the data into a string that will look nice on the page // /n is a line break text = "Name: " + localData.name + ": \n Message:" + localData.message; // innerText changes the value of the span element to include our data lsData.innerText = text; } else { // if not let the user know lsData.innerText = "No data in local storage."; } } function DeleteData() { console.log("Deleting data from local host...."); localStorage.removeItem('siteData'); } </script> </body> </html> </body> </html> [/javascript]
HTML 5 Canvas
The HTML 5 canvas is an HTML element that allows you to draw graphics on the fly with JavaScript. Use it to create cool visualizations, animations and kick ass visual effects. The canvas object has several methods for drawing paths, boxes, circles, text, and adding images. You can also use it to make Javascript Games. It was ment as a replacement for flash. Works best on modern mobile devices and computers. It has fall back features that allows you to display a static image for older computers that don't support it.
Look Below For Some Cool HTML Canvas Examples
How to use the HTML 5 Canvas
Step1: Add the HTML5 Canvas to the screen.
The Id parameter is used grab it with DOM in JavaScript. You can set the height in HTML or you can do that in JavaScript. The box is transparent by default so if you want to see it you will need to add a little CSS. Here are 3 different ways you could do it. Add this to your HTML File.
<canvas id="myCanvas"></canvas>
<canvas id="myCanvas" width="200" height="100"></canvas>
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000; background-color:white;">
Step 2. Grab the canvas with DOM
Create a blank JavaScript file and link it to your HTML document. If you plan to have more than 1 canvas you can use the ID selector.
var canvas = document.getElementById("myCanvas");
Other wise you could just grab the HTML element.
var canvas = document.querySelector('canvas');
Step 3. Set the With & Height of the canvas in JavaScript
Sets the width & height to fit the size of browser
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
You can add an event listener that will change the size of the canvas if someone resizes the browser window.
window.addEventListener('resize', function(){
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
})
Step 4. Create a 2D Drawing Object
Create a drawing object to render the graphic elements on. This is called a 2D drawing context. We will reference this every time we want to add or change something on the canvas .
var ctx = canvas.getContext("2d");
Step 5. Draw Elements On The Screen
Draw a rectangle on the canvas
Draws a solid blue rectangle.
FillRect PARAMETERS (x,y,width,height)
ctx.fillStyle = "blue"; // Rectange Fill Color (Before)
ctx.fillRect(100,100,50,50); // Draws a rectangle
Draws a red rectangle outline.
ctx.strokeStyle = "red"; // Rectangle stroke Color (Before)
ctx.lineWidth = 5; // Stroke Width
ctx.strokeRect(200,200,50,50); // Draws a rectangle outline
Draw a circle on the canvas
ctx.arc(x,y,radius,start angle, end angle, counter clock wise: true/false );
Creates a blue circle.
ctx.beginPath(); // Starts a new path
ctx.fillStyle = "blue"; // Stroke Color
ctx.arc(200,200,30, 0, Math.PI*2, false); // Creates a circle
ctx.fill(); // Fills the circle in with the color
Creates a circle with a red outline.
ctx.beginPath(); // Starts a new path
ctx.fillStyle = "blue"; // Stroke Color
ctx.arc(200,200,30, 0, Math.PI*2, false); // Creates a circle
ctx.fill(); // Fills the circle in with the color
Draw a line on the canvas
ctx.beginPath(); // Starts a new path
ctx.moveTo(100, 100); // (x,y) start point of the line
ctx.lineTo(200, 50); // (x,y) next end point
ctx.lineTo(300, 150); // (x,y) next end point
ctx.lineTo(400, 50); // (x,y) next end point
ctx.strokeStyle = "red"; // Line Stroke Color
ctx.lineCap = "round"; // Makes the end of the line round
ctx.lineJoin = "round"; // Makes the joining of 2 lines round
ctx.lineWidth = 5; // Stroke Width
ctx.stroke(); // Adds the stroke to the line
Draw text on a canvas.
ctx.font = "30px Arial"; // Sets font size and type
ctx.fillText("Hello ", 150, 150); // Creates filled text (text,x,y)
ctx.textAlign = "center"; // Sets text alignmentctx.font = "30px Comic Sans MS";
ctx.strokeText("Word!!", 280, 150); // Creates outlined text (text,x,y)
Draw an image
// Create a function that loads in images
function draw_image(x,y,src)
{
// Create a new image object
image = new Image();
image.src = src;
// Wait until image is loaded to draw it
image.onload = function(){
ctx.drawImage(image, x, y);
}
}
// Call the Image function every time you want to draw one
draw_image(0,0,'image.jpg');
draw_image(100,100,'image.jpg');
Step 6. Animate Elements
Create an animation loop
function animate() {
requestAnimationFrame(animate); // Function that creates an animation loop// Add code that draws and animated objects
}
animate(); // Call animation loop
Create a Controllable Sin Wave With Canvas
Add Dat.Gui Javascript Library To Your HTML Doc
dat.GUI is a lightweight controller library for JavaScript. It creates an interface that allows you to modify varables with sliders. This is helpful to be able to change values and see what it looks like without having to refresh the page.
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/dat-gui/0.7.6/dat.gui.js"></script>
More coming soon!
JavaScript Libraries - What's next?
JQuery
jQuery is a lightweight write less, do more JavaScript library. It makes it easier to write JavaScript with less code. It simplifies some of the more complicated parts of JavaScript. JQuery is tailor-made for selecting HTML elements and performing some kind of action on them. Another great feature of JQuery is browsner compatibility. They did a great job at addressing most of the cross-browser issues in JavaScript. It will work the same on all major browsers. If your looking the first JavaScript library to learn this would be a good place to start.
Anime.js
Anime is a really cool JavaScript library that let you animate anything. You can create really amazing animations with just a few lines of code. It works with CSS properties, SVG, DOM attributes and JavaScript Objects.
LEARN MORE:
Documentation
React
React is an open source JavaScript library for building user interfaces for single page applications. It allows you to create reusable UI components. It was created by a software engineer at Facebook. React is used to build large web applications that change data without needing to refresh the page. React uses a special syntax called JSX. This allows you to mix HTML with JavaScript. Learn More
View.js
View is another framework for creating web applications and user interfaces with JavaScript. It can be combined with other libraries and is a good alternative to Angular and React.
LEARN MORE:
vuejs.org
Tutorials Point
Vue.js - Full Course for Beginners
Angular.js
Angular is another Js library used to create single page web applications. This one is maintained by google.
LEARN MORE
w3 Schools
Node.js
Node.js is designed to build scalable network applications and allows you to run JavaScript on the server. Kinda like PHP but with JavaScript.
Ember.js
Ember.js is a JavaScript framework for creating ambitious web applications. Write less code with templates that automatically update. Ember.js provides tools that let you focus on your app instead of writing the same code you've written a hundred times.
BackBone.js
Backbone.js gives structure to web applications using MVC (Model, View, Controller). Model is part of your code that retrieves and populates data. View is the HTML representation the data and controller allows you to save the state of the application in the URL.
Best JavaScript Books & Online Resources
Best JavaScript Books
Jon Duckett Javascript & JQuery
Eloquent JavaScript (Free)
More Coming Soon
Online Resources
w3Schools
Scotch.io
Tutorial Point
Learn JS
Codecademy.com
More Coming Soon
Adding Comments In JavaScript
Use comments to explain what is going on in your code. They are just there to create notes for yourself and others about what the code does. This will help you remember what you did if you come back to the project after some time. If you work on a team it's important to help others understand your code.
A single line comment start with //. Any text between // and the end of the line will be ignored. A multi line comment starts with a /* and ends with a */
You can also use comments to disable blocks of code. This is good when you are testing to see which part of the code is causing an error. Sometimes you may want to try out another version of code without deleting what you have already done.