-
Hajipur, Bihar, 844101
Hajipur, Bihar, 844101
JS Basics
JS Variables & Operators
JS Data Types & Conversion
JS Numbers & Math
JS Strings
JS Dates
JS Arrays
JS Control Flow
JS Loops & Iteration
JS Functions
JS Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts
The HTML5 Canvas element is a powerful tool for drawing graphics directly in the browser using JavaScript. It allows you to create shapes, images, animations, games, charts, and visual effects without relying on external plugins like Flash. Canvas gives you pixel-level control over graphics, making it ideal for interactive web applications and creative projects.
The <canvas>
element is an HTML tag that provides a drawing surface in the browser. It is essentially a bitmap area, where every pixel can be manipulated with JavaScript. You can draw shapes, text, images, or even build interactive games directly in the browser.
Basic Canvas Example:
<canvas id="myCanvas" width="500" height="300" style="border:1px solid #000;"></canvas>
id
is used to access the canvas in JavaScript.
width
and height
define the drawing area size.
style="border:1px solid #000;"
adds a visible border to reference the canvas size.
To draw on a canvas, you need a drawing context:
let canvas = document.getElementById("myCanvas");
let ctx = canvas.getContext("2d"); // 2D context
getContext("2d")
returns a 2D rendering context, which contains methods for drawing shapes, text, images, and more.
For more advanced graphics, webgl
context is also available for 3D rendering.
ctx.fillStyle = "blue"; // Fill color
ctx.fillRect(50, 50, 150, 100); // x, y, width, height
ctx.strokeStyle = "black"; // Border color
ctx.strokeRect(50, 50, 150, 100);
fillRect()
draws a filled rectangle.
strokeRect()
draws only the outline.
clearRect()
can clear a rectangular area, useful for animations.
ctx.beginPath();
ctx.moveTo(50, 200); // Start point
ctx.lineTo(400, 200); // End point
ctx.strokeStyle = "red";
ctx.lineWidth = 4;
ctx.stroke();
beginPath()
starts a new drawing path.
moveTo()
sets the starting point of the line.
lineTo()
defines the end point.
stroke()
renders the path to the canvas.
ctx.beginPath();
ctx.arc(250, 150, 50, 0, 2 * Math.PI); // x, y, radius, startAngle, endAngle
ctx.fillStyle = "green";
ctx.fill();
ctx.strokeStyle = "black";
ctx.stroke();
arc()
draws a circle or part of a circle.
Angles are in radians (2π radians = 360 degrees).
Circles are useful for charts, game elements, or avatars.
Canvas allows you to draw text in any font and style:
ctx.font = "24px Arial";
ctx.fillStyle = "purple";
ctx.fillText("Hello Canvas", 50, 50);
ctx.strokeStyle = "orange";
ctx.strokeText("Outline Text", 50, 90);
fillText()
fills the text with color.
strokeText()
outlines the text.
Text can be combined with shapes to create labels or UI elements.
You can draw images on a canvas using drawImage()
:
let img = new Image();
img.src = "image.jpg";
img.onload = function() {
ctx.drawImage(img, 50, 120, 150, 100); // x, y, width, height
};
Ensure the image is loaded before drawing.
You can crop and resize images by providing more parameters in drawImage()
.
Canvas is perfect for animations:
let x = 0;
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height); // Clear canvas
ctx.fillStyle = "blue";
ctx.fillRect(x, 50, 50, 50); // Moving square
x += 2;
if (x > canvas.width) x = -50;
requestAnimationFrame(animate);
}
animate();
requestAnimationFrame()
ensures smooth animations.
You can create moving objects, bouncing balls, or interactive games.
Canvas can be interactive:
canvas.addEventListener("click", function(event) {
let rect = canvas.getBoundingClientRect();
let x = event.clientX - rect.left;
let y = event.clientY - rect.top;
ctx.fillStyle = "red";
ctx.fillRect(x - 10, y - 10, 20, 20);
});
Clicking the canvas draws a small square at the clicked position.
Combined with animations, this allows creating drawing apps or simple games.
You can also handle keyboard events:
document.addEventListener("keydown", function(event){
if(event.key === "ArrowRight"){
x += 10; // Move object right
}
});
Fill color: ctx.fillStyle = "color";
Stroke color: ctx.strokeStyle = "color";
Line width: ctx.lineWidth = value;
Gradients for effects:
let gradient = ctx.createLinearGradient(0, 0, 200, 0);
gradient.addColorStop(0, "red");
gradient.addColorStop(1, "yellow");
ctx.fillStyle = gradient;
ctx.fillRect(50, 200, 200, 100);
Gradients and patterns make graphics more visually appealing.
Games: Canvas is used for 2D games like platformers or puzzles.
Charts and Graphs: Dynamic visualizations for dashboards.
Animations: Moving objects, interactive ads, or particles.
Drawing Apps: Paint programs or sketch tools.
Data Visualization: Heatmaps, scatterplots, or animated infographics.
The <canvas>
element allows drawing graphics using JavaScript.
Use getContext("2d")
for 2D graphics; webgl
for 3D.
Draw rectangles, lines, circles, images, and text.
Create animations using requestAnimationFrame()
.
Handle mouse and keyboard events for interactive graphics.
Apply colors, gradients, and strokes for effects.
Canvas is the foundation for games, visualizations, and creative web applications.
Mastering the Canvas API opens up endless possibilities for interactive and graphical web applications.
Create a canvas of size 500x300 and draw a filled blue rectangle at position (50, 50) with width 150 and height 100.
Draw a red line from coordinates (50, 200) to (400, 200) with a line width of 4.
Draw a green circle with a black outline at (250, 150) with a radius of 50.
Add text “Hello Canvas” in purple at position (50, 50) and an outlined orange text “Outline Text” at (50, 90).
Load an image onto the canvas at coordinates (50, 120) with a width of 150 and height of 100, ensuring it only draws after the image loads.
Create an animation where a square moves horizontally across the canvas and loops back when it reaches the end.
Make the canvas interactive so that clicking anywhere draws a small red square at the clicked position.
Implement keyboard control to move a rectangle left, right, up, or down using arrow keys.
Apply a linear gradient from red to yellow on a rectangle positioned at (50, 200) with width 200 and height 100.
Draw multiple shapes (rectangle, circle, and line) and a text label to create a simple “scene” on the canvas, demonstrating layering and color usage.
JS Basics
JS Variables & Operators
JS Data Types & Conversion
JS Numbers & Math
JS Strings
JS Dates
JS Arrays
JS Control Flow
JS Loops & Iteration
JS Functions
JS Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts