JavaScript

coding learning websites codepractice

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 Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JS Graphics


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.

What Are JavaScript Graphics

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.

Why JavaScript Graphics Are Important

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.

JavaScript Graphics Using Canvas

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.

Creating a Canvas Element

<canvas id="myCanvas" width="400" height="300"></canvas>

The canvas itself is empty until JavaScript draws on it.

Getting the Canvas Context

let canvas = document.getElementById("myCanvas");
let ctx = canvas.getContext("2d");

The context is the tool used to draw.

Drawing Shapes on Canvas

Drawing a Rectangle

ctx.fillStyle = "blue";
ctx.fillRect(50, 50, 150, 100);

This draws a filled rectangle.

Drawing an Outline Rectangle

ctx.strokeStyle = "red";
ctx.strokeRect(50, 200, 150, 80);

This draws only the border.

Clearing the Canvas

ctx.clearRect(0, 0, canvas.width, canvas.height);

This removes everything drawn on the canvas.

Drawing Lines and Paths

ctx.beginPath();
ctx.moveTo(20, 20);
ctx.lineTo(200, 100);
ctx.stroke();

Paths allow complex shapes to be drawn.

Drawing Circles

ctx.beginPath();
ctx.arc(200, 150, 50, 0, Math.PI * 2);
ctx.fillStyle = "green";
ctx.fill();

Circles are created using arcs.

Drawing Text on Canvas

ctx.font = "20px Arial";
ctx.fillStyle = "black";
ctx.fillText("Hello Graphics", 100, 50);

Text is treated as a drawable object.

Drawing Images

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.

Canvas Animations

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.

JavaScript Graphics Using SVG

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.

Basic SVG Example

<svg width="300" height="200">
    <circle cx="150" cy="100" r="50" fill="orange"></circle>
</svg>

SVG elements are directly visible and editable.

Manipulating SVG with JavaScript

let circle = document.querySelector("circle");
circle.setAttribute("fill", "blue");

SVG elements behave like normal DOM elements.

SVG Shapes

Common SVG shapes include:

  • Rectangle

  • Circle

  • Ellipse

  • Line

  • Polygon

  • Path

Each shape has its own attributes.

SVG Text Example

<svg width="300" height="100">
    <text x="50" y="50" font-size="20">SVG Text</text>
</svg>

SVG text scales smoothly with zoom.

Canvas vs SVG

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.

Practical Example: Simple Bar Chart with Canvas

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.

Practical Example: Interactive SVG Button

<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.

Common Mistakes

  • 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.

Best Practices

  • 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.

Performance Considerations

Graphics can be resource intensive.

  • Reduce unnecessary redraws

  • Optimize image sizes

  • Limit complex paths

  • Cache static drawings

Performance tuning is essential for large applications.

Real World 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.

Browser Support

Canvas and SVG are supported by all modern browsers, including mobile browsers. This makes JavaScript graphics reliable for production use.

Summary of JS Graphics

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.


Practice Questions

  1. Create a canvas and draw a blue rectangle at position (50, 50) with width 150 and height 100.

  2. Draw a red line from (50, 200) to (400, 200) with a line width of 5.

  3. Draw a green circle with a black border at (250, 150) and radius 50.

  4. Draw a polygon with three points forming a triangle and fill it with purple color.

  5. Create a linear gradient from red to yellow and apply it to a rectangle.

  6. Animate a square moving horizontally across the canvas and looping back to the start when it reaches the edge.

  7. Capture mouse clicks on the canvas and draw a small circle at the clicked position.

  8. Make an interactive canvas where moving the mouse draws a circle following the cursor.

  9. Draw multiple shapes (rectangle, circle, and line) in a single scene, demonstrating layering.

  10. Using a library like p5.js, create a canvas that draws multiple colored circles at random positions each time the page loads.


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

JavaScript

online coding class codepractice

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 Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top