Lesson 20 of 21 – HTML Canvas
95%

HTML Canvas

The HTML <canvas> element is used to draw graphics on a web page. Graphics are created using JavaScript.

Note: The canvas element is only a container. JavaScript is required to draw graphics.
What is HTML Canvas?

HTML Canvas allows you to draw:

  • Lines
  • Rectangles
  • Circles
  • Text
  • Images
  • Animations

<canvas
id="myCanvas"
width="200"
height="100">

</canvas>

Canvas Area

A canvas is a rectangular drawing area.


<canvas
id="canvas1"
width="300"
height="150"
style="border:1px solid black;">

</canvas>

Always specify:

  • id
  • width
  • height
Getting the Context

JavaScript accesses the drawing area using getContext().


var c=
document.getElementById(
"myCanvas"
);

var ctx=
c.getContext("2d");

The 2D context is used for drawing.

Draw a Line

ctx.moveTo(
0,
0
);

ctx.lineTo(
200,
100
);

ctx.stroke();

The stroke() method draws the line.

Draw a Circle

ctx.beginPath();

ctx.arc(
95,
50,
40,
0,
2*Math.PI
);

ctx.stroke();

The arc() method creates circles and arcs.

Draw a Rectangle

The fillRect() method draws a filled rectangle.


ctx.fillRect(

20,

20,

150,

100

);

Parameters:

  • X Position
  • Y Position
  • Width
  • Height
Draw Text

Canvas can display text.


ctx.font=
"30px Arial";

ctx.fillText(

"Hello",

20,

50

);

fillText() draws filled text.

Draw Images

Images can be displayed inside a canvas.


var img=

document.getElementById(

"img1"

);

ctx.drawImage(

img,

10,

10

);

drawImage() places the image on the canvas.

Canvas Features
Feature Purpose
Line Draw lines
Rectangle Draw boxes
Circle Draw circles
Text Display text
Image Display images
Fill Fill color
Stroke Draw outlines
Animation Create motion
Key Points
  • Canvas draws graphics.
  • JavaScript is required.
  • Supports lines.
  • Supports rectangles.
  • Supports circles.
  • Supports text.
  • Supports images.
  • Supports animation.
  • Supports games.
  • Supports charts.

🧠 Quiz

Which method is used to get the 2D drawing context?