HTML5 introduced several powerful APIs (Application Programming Interfaces) that enhance web applications. These APIs allow developers to create interactive, dynamic, and feature-rich websites without relying on third-party plugins like Flash.
In this chapter, we will explore some of the most commonly used HTML5 APIs, including:
- Canvas API (for drawing graphics)
- Geolocation API (for getting the user’s location)
- Drag and Drop API (for moving elements)
- Web Storage API (for storing data in the browser)
1. Canvas API (<canvas>
)
The Canvas API allows developers to draw graphics, animations, and charts directly on a web page using JavaScript.
1.1 Basic <canvas>
Structure
To use the Canvas API, you need:
- A
<canvas>
element in HTML - JavaScript to draw on it
Example:
<canvas id="myCanvas" width="400" height="200" style="border:1px solid black;"></canvas>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
// Draw a blue rectangle
ctx.fillStyle = "blue";
ctx.fillRect(50, 50, 150, 100);
</script>
1.2 Drawing Shapes on Canvas
fillRect(x, y, width, height)
: Draws a filled rectanglestrokeRect(x, y, width, height)
: Draws an outlined rectanglebeginPath()
,moveTo(x, y)
,lineTo(x, y)
,stroke()
: Draws linesarc(x, y, radius, startAngle, endAngle)
: Draws circles
Example: Drawing a Circle
<canvas id="circleCanvas" width="300" height="300"></canvas>
<script>
var canvas = document.getElementById("circleCanvas");
var ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.arc(100, 100, 50, 0, 2 * Math.PI);
ctx.fillStyle = "red";
ctx.fill();
</script>
2. Geolocation API
The Geolocation API allows websites to access the user’s current location. This is commonly used in maps, weather apps, and location-based services.
2.1 Getting User Location
<button onclick="getLocation()">Get My Location</button>
<p id="location"></p>
<script>
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
document.getElementById("location").innerHTML = "Geolocation is not supported.";
}
}
function showPosition(position) {
document.getElementById("location").innerHTML =
"Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
</script>
2.2 Watching User Location (Real-time Updates)
The watchPosition()
function tracks the user’s location continuously.
navigator.geolocation.watchPosition(function(position) {
console.log("Latitude: " + position.coords.latitude);
console.log("Longitude: " + position.coords.longitude);
});
3. Drag and Drop API
The Drag and Drop API lets users move elements on a webpage using a mouse.
3.1 Basic Drag and Drop Example
<p>Drag the box below:</p>
<div id="dragBox" draggable="true" ondragstart="drag(event)"
style="width:100px; height:100px; background-color:lightblue;"></div>
<div id="dropZone" ondragover="allowDrop(event)" ondrop="drop(event)"
style="width:200px; height:200px; border:2px dashed black; margin-top:20px;"></div>
<script>
function allowDrop(event) {
event.preventDefault();
}
function drag(event) {
event.dataTransfer.setData("text", event.target.id);
}
function drop(event) {
event.preventDefault();
var data = event.dataTransfer.getData("text");
event.target.appendChild(document.getElementById(data));
}
</script>
How it Works?
- The
draggable="true"
attribute makes an element draggable. ondragstart
captures the element being dragged.ondragover
prevents default behavior so dropping is allowed.ondrop
handles placing the element in the target location.
4. Web Storage API (localStorage
& sessionStorage
)
Web Storage API allows developers to store data in the user’s browser.
localStorage
: Data persists even after closing the browser.sessionStorage
: Data is deleted after closing the tab or browser.
4.1 Storing and Retrieving Data with localStorage
<input type="text" id="nameInput" placeholder="Enter your name">
<button onclick="saveName()">Save Name</button>
<button onclick="showName()">Show Name</button>
<p id="displayName"></p>
<script>
function saveName() {
var name = document.getElementById("nameInput").value;
localStorage.setItem("userName", name);
}
function showName() {
var storedName = localStorage.getItem("userName");
document.getElementById("displayName").innerHTML = "Stored Name: " + storedName;
}
</script>
4.2 sessionStorage
Example
<button onclick="saveSession()">Save to Session</button>
<button onclick="showSession()">Show Session Data</button>
<p id="sessionData"></p>
<script>
function saveSession() {
sessionStorage.setItem("sessionKey", "This is session data");
}
function showSession() {
var data = sessionStorage.getItem("sessionKey");
document.getElementById("sessionData").innerHTML = data;
}
</script>
5. Summary Table of HTML5 APIs
API | Purpose | Example Usage |
---|---|---|
Canvas API | Draw graphics, charts, animations | Game development, data visualization |
Geolocation API | Get user’s location | Maps, location-based services |
Drag and Drop API | Move elements within the page | Interactive UIs, file uploads |
Web Storage API | Store data in the browser | User preferences, form data |
6. Best Practices for Using HTML5 APIs
✔ Always check browser support using if(navigator.geolocation)
or if(localStorage)
.
✔ Handle errors properly, such as when the user denies location access.
✔ Use sessionStorage for temporary data and localStorage for long-term storage.
✔ Limit stored data in localStorage to avoid performance issues.
✔ When using Canvas API, optimize rendering for performance.
Conclusion
In this chapter, we explored:
- Canvas API for drawing graphics
- Geolocation API to get user location
- Drag and Drop API for interactive elements
- Web Storage API to store user data
These HTML5 APIs make web applications more powerful and interactive.