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 Canvas


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.

What is the Canvas?

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.

Accessing the Canvas with JavaScript

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.

Drawing Basic Shapes

1. Rectangle

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.

2. Line

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.

3. Circle

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.

Drawing Text

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.

Drawing Images

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

Animation on Canvas

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.

Handling Mouse and Keyboard Events

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
    }
});

Colors, Gradients, and Styles

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

Real-World Uses of Canvas

  1. Games: Canvas is used for 2D games like platformers or puzzles.

  2. Charts and Graphs: Dynamic visualizations for dashboards.

  3. Animations: Moving objects, interactive ads, or particles.

  4. Drawing Apps: Paint programs or sketch tools.

  5. Data Visualization: Heatmaps, scatterplots, or animated infographics.

Summary of the Tutorial

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


Practice Questions

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

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

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

  4. Add text “Hello Canvas” in purple at position (50, 50) and an outlined orange text “Outline Text” at (50, 90).

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

  6. Create an animation where a square moves horizontally across the canvas and loops back when it reaches the end.

  7. Make the canvas interactive so that clicking anywhere draws a small red square at the clicked position.

  8. Implement keyboard control to move a rectangle left, right, up, or down using arrow keys.

  9. Apply a linear gradient from red to yellow on a rectangle positioned at (50, 200) with width 200 and height 100.

  10. Draw multiple shapes (rectangle, circle, and line) and a text label to create a simple “scene” on the canvas, demonstrating layering and color usage.


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