-
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
Graphics play an important role in modern web applications. From charts and animations to games and interactive visuals, JavaScript provides powerful ways to draw and control graphics directly in the browser. Instead of relying on images alone, developers can create dynamic, responsive, and interactive graphics that react to user actions and data changes.
In this tutorial, you will learn what JavaScript graphics are, why they are important, the main approaches used for graphics in JavaScript, how they work, practical examples, common mistakes, best practices, and real world use cases.
JavaScript graphics refer to visual elements created or controlled using JavaScript inside a web page. These graphics are generated programmatically rather than being static images. JavaScript can draw shapes, text, images, charts, and animations using browser technologies.
The two most commonly used technologies for JavaScript graphics are:
HTML Canvas
SVG
Both are widely supported and serve different purposes.
JavaScript graphics are important because they allow developers to:
Create interactive visual content
Build charts and dashboards
Develop browser based games
Animate user interfaces
Visualize data in real time
Improve user engagement
Without JavaScript graphics, modern web applications would feel static and limited.
The HTML Canvas element provides a drawing surface where JavaScript can render graphics using pixels. It is best suited for animations, games, and performance intensive graphics.
<canvas id="myCanvas" width="400" height="300"></canvas>
The canvas itself is empty until JavaScript draws on it.
let canvas = document.getElementById("myCanvas");
let ctx = canvas.getContext("2d");
The context is the tool used to draw.
ctx.fillStyle = "blue";
ctx.fillRect(50, 50, 150, 100);
This draws a filled rectangle.
ctx.strokeStyle = "red";
ctx.strokeRect(50, 200, 150, 80);
This draws only the border.
ctx.clearRect(0, 0, canvas.width, canvas.height);
This removes everything drawn on the canvas.
ctx.beginPath();
ctx.moveTo(20, 20);
ctx.lineTo(200, 100);
ctx.stroke();
Paths allow complex shapes to be drawn.
ctx.beginPath();
ctx.arc(200, 150, 50, 0, Math.PI * 2);
ctx.fillStyle = "green";
ctx.fill();
Circles are created using arcs.
ctx.font = "20px Arial";
ctx.fillStyle = "black";
ctx.fillText("Hello Graphics", 100, 50);
Text is treated as a drawable object.
let img = new Image();
img.src = "logo.png";
img.onload = function () {
ctx.drawImage(img, 50, 50, 100, 100);
};
Images can be resized and positioned easily.
Animations are created by repeatedly clearing and redrawing the canvas.
let x = 0;
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillRect(x, 50, 50, 50);
x += 2;
requestAnimationFrame(animate);
}
animate();
This technique is commonly used in games.
SVG stands for Scalable Vector Graphics. Unlike Canvas, SVG graphics are vector based and remain sharp at any resolution. SVG elements are part of the DOM and can be styled and manipulated using JavaScript and CSS.
<svg width="300" height="200">
<circle cx="150" cy="100" r="50" fill="orange"></circle>
</svg>
SVG elements are directly visible and editable.
let circle = document.querySelector("circle");
circle.setAttribute("fill", "blue");
SVG elements behave like normal DOM elements.
Common SVG shapes include:
Rectangle
Circle
Ellipse
Line
Polygon
Path
Each shape has its own attributes.
<svg width="300" height="100">
<text x="50" y="50" font-size="20">SVG Text</text>
</svg>
SVG text scales smoothly with zoom.
Choosing between Canvas and SVG depends on the use case.
Canvas is better when:
Creating games
Handling thousands of objects
Running animations frequently
SVG is better when:
Working with charts
Creating scalable icons
Needing DOM interaction
Styling with CSS
Both technologies are powerful and widely used.
let values = [120, 90, 150, 80];
let startX = 50;
values.forEach(value => {
ctx.fillRect(startX, 250 - value, 40, value);
startX += 60;
});
This is the foundation of data visualization.
<svg width="200" height="60">
<rect id="btn" x="10" y="10" width="180" height="40" fill="green"></rect>
<text x="70" y="38" fill="white">Click</text>
</svg>
document.getElementById("btn").addEventListener("click", function () {
alert("Button clicked");
});
This shows how SVG integrates with events.
Forgetting to set canvas width and height
Redrawing without clearing the canvas
Using Canvas for static graphics unnecessarily
Overusing SVG for heavy animations
Ignoring performance optimization
Avoiding these mistakes improves graphics quality.
Choose Canvas or SVG wisely
Optimize redraw logic
Use requestAnimationFrame for animations
Keep code modular
Test across screen sizes
Following these practices ensures smooth visuals.
Graphics can be resource intensive.
Reduce unnecessary redraws
Optimize image sizes
Limit complex paths
Cache static drawings
Performance tuning is essential for large applications.
JavaScript graphics are used in:
Online games
Data dashboards
Chart libraries
Drawing tools
Visual editors
Educational applications
Most modern web apps rely on graphics heavily.
Canvas and SVG are supported by all modern browsers, including mobile browsers. This makes JavaScript graphics reliable for production use.
JavaScript graphics allow developers to create dynamic, interactive, and visually rich web applications. Using technologies like Canvas and SVG, JavaScript can draw shapes, text, images, and animations directly in the browser. Canvas is ideal for performance intensive graphics and animations, while SVG is perfect for scalable and interactive visuals. By understanding both approaches, their strengths, and best practices, you can build engaging graphics that enhance user experience and bring modern web applications to life.
Create a canvas and draw a blue rectangle at position (50, 50) with width 150 and height 100.
Draw a red line from (50, 200) to (400, 200) with a line width of 5.
Draw a green circle with a black border at (250, 150) and radius 50.
Draw a polygon with three points forming a triangle and fill it with purple color.
Create a linear gradient from red to yellow and apply it to a rectangle.
Animate a square moving horizontally across the canvas and looping back to the start when it reaches the edge.
Capture mouse clicks on the canvas and draw a small circle at the clicked position.
Make an interactive canvas where moving the mouse draws a circle following the cursor.
Draw multiple shapes (rectangle, circle, and line) in a single scene, demonstrating layering.
Using a library like p5.js, create a canvas that draws multiple colored circles at random positions each time the page loads.
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
