Canvas clearRect: HTML5

Rectangle is the only primitive type supported by canvas.

It has 3 functions:
strokeRect(x, y, w, h);
fillRect(x, y, w, h);
clearRect(x, y, w, h);

In our previous video tutorials we’ve seen using strokeRect and fillRect methods. In this short video tutorial, we’re illustrating clearRect() method.

clearRect method erases the given rectangle and makes the area fully transparent.

index.html and myStyle.css files are kept same as illustrated in previous video tutorial: Canvas State: HTML5

JavaScript file
myScript.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
window.onload = canvas;
 
function canvas()
{
var myCanvas = document.getElementById("myCanvas");
 
if( myCanvas && myCanvas.getContext("2d") ) 
{
var context         = myCanvas.getContext("2d");
 
context.fillStyle = "red";
context.fillRect(10, 10, 75, 75);
 
context.fillStyle = "blue";
context.fillRect(90, 10, 75, 75);
 
context.clearRect(5, 40, 200, 40)
}
}

Here we first draw 2 rectangles: red and blue.
Next clear part of these two rectangles using clearRect method.

We start clearRect() from 5px x-axis, and 40px y-axis; with a width of 200px, so that it covers both red and blue rectangles.

Canvas clearRect: HTML5


[youtube https://www.youtube.com/watch?v=W1W5LEGeqjI]

YouTube Link: https://www.youtube.com/watch?v=W1W5LEGeqjI [Watch the Video In Full Screen.]



Advantages of clearRect() method may not seem obvious at first, but will be helpful in game development – to draw transparent paths between your drawings/graphics.

Canvas State: HTML5

Today lets learn about canvas states, which will come handy once we start drawing complex shapes/graphics. Canvas state keeps track of current values of lineWidth, strokeStyle, fillStyle, lineCap, transformation matrix, clipping regions etc.

Backup-Recovery

Each time we save a state, it’s pushed onto a stack of saved states from which we can restore the state later.

HTML file
index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
< !DOCTYPE HTML>
<html>
<head>
<title>Canvas: HTML5</title>
<meta charset="utf-8"/>
<link href="myStyle.css" rel="stylesheet" />
<script src="myScript.js"></script>
</head>
<body>
 
<canvas id="myCanvas" width="200" height="200">
  Upgrade Browser
 </canvas>
 
</body>
</html>

HTML5 document with a canvas element which has an id and 200px width and height.
It’s also attached with an external stylesheet and a javascript file.

StyleSheet file
myStyle.css

1
2
3
canvas {
border: 2px dotted black;
}

Here we’re selecting canvas element and assigning it a 2px thick black dotted border.

JavaScript file
myScript.js

1
2
3
4
5
6
7
8
9
10
context.fillStyle   = "red";
context.fillRect(10, 10, 50, 50);
context.save();
 
context.fillStyle   = "blue";
context.fillRect(20, 20, 75, 75);
 
 
context.restore();
context.fillRect(30, 30, 100, 100);

We have 3 rectangle boxes.
First one is filled with red color.
Second one is filled with blue color.

Using save() method, we have saved the fillStyle property value.
Now we restore fillStyle property before drawing the third rectangle.
Saved canvas state has fillStyle as red, so our third rectangle gets red color.

JavaScript file
myScript.js

1
2
3
4
5
6
7
8
9
10
11
context.fillStyle   = "red";
context.fillRect(10, 10, 50, 50);
context.save();
 
context.fillStyle   = "blue";
context.fillRect(20, 20, 75, 75);
context.save();
 
context.restore();
context.restore();
context.fillRect(30, 30, 100, 100);

Here we’re saving canvas states twice.

Canvas State Stack
blue left_arrow 2nd in.

red left_arrow 1st in.

Canvas State Calls
1st restore call right_red_arrow blue

2nd restore call right_red_arrow red

Hence, now third rectangle will be red colored.

Canvas State: HTML5


[youtube https://www.youtube.com/watch?v=1oBlAhoa9zI]

YouTube Link: https://www.youtube.com/watch?v=1oBlAhoa9zI [Watch the Video In Full Screen.]



Full JavaScript Code
myScript.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
window.onload = canvas;
 
function canvas()
{
var myCanvas = document.getElementById("myCanvas");
 
if( myCanvas && myCanvas.getContext("2d") ) 
{
var context         = myCanvas.getContext("2d");
 
context.fillStyle   = "red";
context.fillRect(10, 10, 50, 50);
context.save();
 
context.fillStyle   = "blue";
context.fillRect(20, 20, 75, 75);
context.save();
 
context.restore();
context.restore();
context.fillRect(30, 30, 100, 100);
 
}
}

Related read:
Canvas Basics: HTML5
Draw Rectangle: HTML5 Canvas

Instantly we could think of building “undo” feature for our drawing board application with the help of canvas state stack!

Draw Rectangle: HTML5 Canvas

This video tutorial illustrates the drawing of rectangle with styling.

Tutorial Includes:
Drawing rectangle.
Specifying x-axis and y-axis for drawing rectangle.
Specifying width and height for drawing rectangle.
Filling the border(strokeStyle) with color.
Filling the body(fillStyle) of rectangle with color.
Specifying the border width(lineWidth). etc

HTML5-canvas-rectangle-xaxis-yaxis


HTML file
index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
< !DOCTYPE HTML>
<html>
<head>
<title>Canvas: HTML5</title>
<meta charset="utf-8"/>
<link href="myStyle.css" rel="stylesheet" />
<script src="myScript.js"></script>
</head>
<body>
 <canvas id="myCanvas" width="200" height="200">
  Upgrade Browser
 </canvas>
</body>
</html>

Here we’ve attached a stylesheet and a script file.
It also has a canvas element with an id of myCanvas, with 200px width and height.

CSS file
myStyle.css

1
2
3
canvas {
border: 2px dotted black;
}

We are assigning a 2px wide black dotted border to the canvas element.

JavaScript file
myScript.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
window.onload = canvas;
 
function canvas()
{
var myCanvas = document.getElementById("myCanvas");
 
if( myCanvas && myCanvas.getContext("2d") ) 
{
var context = myCanvas.getContext("2d");
context.lineWidth   = 2;
context.strokeStyle = "red";
context.strokeRect(10, 10, 100, 100);
 
context.fillStyle = "blue";
context.fillRect(10, 10, 100, 100);
}
}

Related Read: Canvas Basics: HTML5

Once the index.html file loads, it calls a method called canvas.

Validation
Inside canvas method, we check if the canvas element is actually present on the webpage. If present, we check if the browser actually supports context object.

If both of them are present, then we make use of the API provided by context object and draw the rectangle and assign some styling to it.

Defaults
By default, lineWidth has 1px. In our example we’re setting it to 2px.
By default, strokeStyle and fillStyle has black color. In our example, we’re setting it to red and blue respectively.

Result
Canvas element has some margin by default. And the top left corner of canvas is considered x-axis = 0 and y-axis = 0.
In our example, we are placing our rectangle at 10px x-axis and 10px y-axis, with 100px width and height.

With all these, we get a 100px wide and 100px tall, blue rectangle with a red border.

Draw Rectangle: HTML5 Canvas


[youtube https://www.youtube.com/watch?v=i5aZGbbFwDI]

YouTube Link: https://www.youtube.com/watch?v=i5aZGbbFwDI [Watch the Video In Full Screen.]



Now you maybe thinking, we’ll have fillCircle and strokeCircle, fillTriangle and strokeTriangle methods to draw circles and triangles. But NO. We don’t have such methods.
We need to achieve shapes other than rectangle using paths and lines. Lets see how it can be done in our coming video tutorials. Stay subscribed.

Canvas Basics: HTML5

We shall start exploring more about Canvas element of HTML5.
It’s designed to draw graphics on the fly, using Javascript.

Canvas is like a placeholder for graphics. We place a context upon canvas, upon which we draw our graphics – lines, circles, triangle, pictures etc.

HTML file
index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
< !DOCTYPE HTML>
<html>
 <head>
  <title>Canvas: HTML5</title>
  <meta charset="utf-8"/>
  <link href="myStyle.css" rel="stylesheet"/>
 </head>
 <body>
 
  <canvas id="holder" width="300" height="200">
    Please upgrade your browser!
  </canvas>
 
</body>
</html>

Here we have attached a style sheet to index.html
and we have the canvas element with an id, width and a height property applied to it.

We can specify some text in-between the opening and closing canvas tag, which shows up in the browser which doesn’t support HTML5’s canvas element.

CSS file
myStyle.css

1
2
3
canvas {
border: 3px groove black;
}

Here we’re applying some basic style to our canvas.

Since canvas is transparent by nature, we can’t see it unless we give it a border or fill some color into it. So, using CSS we apply 3px wide black border, for the purpose of illustration.

Canvas Basics: HTML5


[youtube https://www.youtube.com/watch?v=2lJqB9RikYo]

YouTube Link: https://www.youtube.com/watch?v=2lJqB9RikYo [Watch the Video In Full Screen.]



CSS width and height
We could even assign width and height property of canvas element via CSS, but it is not the proper way to do it.

We must give width and height property inside HTML document itself – as canvas property.

If you assign width and height via CSS, it’ll either stretch or shrink depending on the actual canvas width and height: which looks weird.

Realtime Location Tracking – Google Maps: HTML5

In this video tutorial, we show you how we can keep track of the visitor and locate him/her on Google Maps using geolocation API of HTML5.

This video tutorial is a continuation of previous videos, so please make sure to watch them before this:
HTML5 – Getting Started Guide
Geolocation API – Success Handler: HTML5
Geolocation API – Error Handle: HTML5
Google Maps Integration: HTML5
Adding Pin/Marker To Google Map: HTML5
Add Popup message To Google Map Pin: HTML5

JavaScript file
mySript.js

if( navigator.geolocation )
    {
        var optn = {
enableHighAccuracy: true,
            timeout: Infinity,
            maximumAge: 0   
        };
         var watchID = navigator.geolocation.watchPosition(success, fail, optn);    
    }
    
    else
     $("p").html("HTML5 Not Supported");

$("button").click(function(){
    
    if(watchID)
     navigator.geolocation.clearWatch(watchID);
     
    watchID = null;
    return false;
});

Here we are setting the 3rd parameter of watchPosition() method.
We’re enabling HighAccuracy, setting timeout to Infinity – i.e., it’ll keep looking for the location information for ever or until it gets it. We can set this to some numerical value and it’ll check till then before it’ll show a “Timed out” message to the user. maximumAge is set to 0, so that it fetches new location each time it’s asked for. If we set it to Infinity, it’ll forever show the cached data and will never fetch or update the new location information.

watchPosition() is a geolocation method, which keeps watching/fetching new user location data. This would be helpful for tracking users location information in realtime.

HTML file
index.html

<!doctype html>
<html>
<head>
<title>Geolocation API: Technotip.com</title>
<meta charset="utf-8"/>
<link href="css/myStyle.css" rel="stylesheet"/>
<script src="js/jquery-1.10.1.min.js"></script>
<script src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script src="js/myScript.js"></script>
</head>
<body>
<p id="map"></p>
<button>Stop</button>
</body>
</html>

We also have a stop button added to our index.html page, once the user clicks on that button, we call clearWatch() method of geolocation API and ask watchPosition() method to stop tracking the users location.

Video Tutorial: Realtime Location Tracking – Google Maps: HTML5


[youtube https://www.youtube.com/watch?v=qYFkPFtfgdI]

YouTube Link: https://www.youtube.com/watch?v=qYFkPFtfgdI [Watch the Video In Full Screen.]



By combining all the things you have learnt in this Google MAPs and geolocation API video tutorial series, you can build real time location tracking applications, which returns users location on a map, pin points it. Combining this, you could store users initial and final location, store it in database, pin point both locations on Google MAP and show them the distance or route etc.

Source Code: Full JavaScript file

mySript.js

var watchID = null;
$(document).ready(function(){
    var optn = {
enableHighAccuracy: true,
            timeout: Infinity,
            maximumAge: 0   
        };
    if( navigator.geolocation )
     navigator.geolocation.watchPosition(success, fail, optn);
    else
     $("p").html("HTML5 Not Supported");
$("button").click(function(){
    
    if(watchID)
     navigator.geolocation.clearWatch(watchID);
     
    watchID = null;
    return false;
});
    
});

function success(position)
{
    var googleLatLng = new google.maps.LatLng(position.coords.latitude, 
                        position.coords.longitude);
    var mapOtn={
zoom:10,
center:googleLatLng,
mapTypeId:google.maps.MapTypeId.ROAD
    };
    
    var Pmap=document.getElementById("map");
    
    var map=new google.maps.Map(Pmap, mapOtn);
    addMarker(map, googleLatLng, "Technotip.com", 
                  "SATISH B
About Me:https://technotip.com/about/");
}

function addMarker(map, googleLatLng, title, content){
    var markerOptn={
position:googleLatLng,
map:map,
title:title,
animation:google.maps.Animation.DROP
    };
    
    var marker=new google.maps.Marker(markerOptn);
    
    var infoWindow=new google.maps.InfoWindow({ content: content, 
                                                   position: googleLatLng});
    google.maps.event.addListener(marker, "click", function(){
        infoWindow.open(map);
    });                                                
}

function fail(error)
{
    var errorType={
0:"Unknown Error",
1:"Permission denied by the user",
2:"Position of the user not available",
3:"Request timed out"
    };
    
    var errMsg = errorType[error.code];
    
    if(error.code == 0 || error.code == 2){
        errMsg = errMsg+" - "+error.message;
    }
    
    $("p").html(errMsg);
}

You can integrate MAPs feature into your existing application and release this module to your users and impress them by telling their location or you can show other users nearby to their location, this would amaze some, as to how you could know about the person living nearby :-)

Remember the position.coords.accuracy property, which returns the accuracy value in meters?
Using this value, show all the users present around a users location with that accuracy(position.coords.accuracy).

Happy learning!