The HTML <canvas> element provides a bitmap drawing surface. JavaScript gets a drawing context from that element and uses the Canvas API to draw lines, rectangles, arcs, text, images, charts, animations and other graphics.
For 2D graphics, the basic pattern is: add a canvas with explicit width and height, select it in JavaScript, call getContext('2d'), and then use methods such as fillRect(), lineTo() or arc().
<canvas id="my_canvas" width="500" height="200">
Your browser does not support the canvas element.
</canvas>
<script>
const canvas = document.getElementById('my_canvas');
const ctx = canvas.getContext('2d');
ctx.fillStyle = '#0d6efd';
ctx.fillRect(20, 20, 160, 80);
</script>
The canvas coordinate system starts at the top-left corner. The X coordinate increases from left to right and the Y coordinate increases from top to bottom.
width and height HTML attributes define the drawing surface dimensions. If omitted, the default canvas size is 300 by 150.width or height after drawing resets the drawing surface and the rendering state.const canvas = document.getElementById('my_canvas');
const ctx = canvas.getContext('2d');
if (ctx) {
ctx.fillStyle = 'green';
ctx.fillRect(10, 10, 120, 60);
}
getContext('2d') returns a CanvasRenderingContext2D object when the 2D context is available. The drawing methods and properties used throughout this tutorial are called on that context object.
A canvas is transparent by default, so a border can make its dimensions easier to see while learning.
<canvas id="my_canvas"
width="500"
height="200"
style="border:1px solid #000;max-width:100%;height:auto;"></canvas>
A typical line begins with a path, moves to a starting coordinate, adds one or more line segments, and then strokes the path.
const ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.moveTo(20, 30);
ctx.lineTo(220, 100);
ctx.lineWidth = 4;
ctx.strokeStyle = '#333';
ctx.stroke();
| Canvas API | Purpose |
|---|---|
moveTo(x, y) | Moves the current path position without drawing a line. |
lineTo(x, y) | Adds a straight line from the current point to a new point. |
lineWidth | Sets the width used for stroked lines. |
lineCap | Controls the shape of line ends. |
lineJoin | Controls how connected line segments join. |
miterLimit | Limits long miter joins. |
setLineDash() | Sets a repeating dash-and-gap pattern. |
lineDashOffset | Shifts the starting position of a dash pattern. |
closePath() | Adds a path segment back toward the start of the current subpath. |
strokeStyle | Sets the color, gradient or pattern used for strokes. |
Try the line drawing demo | Marching ants dashed-border animation
| Canvas API | Purpose |
|---|---|
rect(x, y, width, height) | Adds a rectangle to the current path; call stroke() or fill() to render it. |
fillRect(x, y, width, height) | Immediately draws a filled rectangle. |
strokeRect(x, y, width, height) | Immediately draws the rectangle outline. |
clearRect(x, y, width, height) | Clears pixels in the specified rectangle to transparent black. |
ctx.beginPath();
ctx.arc(100, 100, 60, 0, Math.PI * 2);
ctx.stroke();
For arc(x, y, radius, startAngle, endAngle, counterclockwise), angles are measured in radians. A full circle runs through Math.PI * 2 radians.
| Canvas API | Purpose |
|---|---|
arc() | Adds a circular arc to the current path. |
arcTo() | Adds an arc using tangent points. |
quadraticCurveTo() | Adds a quadratic Bézier curve with one control point. |
bezierCurveTo() | Adds a cubic Bézier curve with two control points. |
Try the arc and circle demo | Change arc start and end angles
| Canvas API | Purpose |
|---|---|
font | Sets the font style, size and family. |
fillText() | Draws filled text at the specified coordinates. |
strokeText() | Draws the outline of text. |
textAlign | Controls horizontal text alignment. |
textBaseline | Controls how text aligns vertically to the Y coordinate. |
| Canvas API | Purpose |
|---|---|
fillStyle | Sets the color, gradient or pattern used for fills. |
createLinearGradient() | Creates a gradient along a straight line. |
createRadialGradient() | Creates a gradient using two circles. |
| Canvas property | Purpose |
|---|---|
shadowColor | Sets the shadow color. |
shadowOffsetX | Moves the shadow horizontally. |
shadowOffsetY | Moves the shadow vertically. |
shadowBlur | Sets the shadow blur level. |
Canvas shadow demo | Interactive shadow demo
Transformations change the drawing coordinate system for operations that follow them. Use save() and restore() when you want a transformation to affect only part of a drawing.
rotate() | translate() | transform()
After learning the drawing primitives, these existing examples show how they can be combined into larger graphics:
Canvas drawings are pixels rather than individual DOM elements, so interaction usually requires listening for events on the canvas and translating pointer coordinates into the drawing's coordinate system.
See mouse coordinates and events on Canvas and JavaScript events.
No. Canvas is a browser API and works directly with JavaScript. Older examples may use jQuery to select the canvas element, but native DOM methods are sufficient:
const canvas = document.querySelector('#my_canvas');
const ctx = canvas.getContext('2d');
The older jQuery approach remains possible, but there is normally no benefit to loading jQuery only to access the canvas element. See the existing Canvas JavaScript and jQuery comparison.
Graphics drawn into Canvas are pixels and do not automatically provide the same semantic structure as HTML elements. Do not use Canvas as the only representation of important text, controls or data.
<canvas> tags when appropriate.<canvas> element creates the surface; JavaScript performs the drawing.beginPath() when starting an independent path and accidentally connecting shapes.lineTo() but forgetting stroke() or fill().It provides a drawing surface that scripts can use for 2D graphics, charts, games, animations, image processing and other pixel-based graphics.
For normal dynamic drawing, yes. HTML creates the canvas element, while JavaScript calls the Canvas API to draw into it.
It requests the canvas 2D rendering context. That object provides the methods and properties used to draw shapes, paths, text and images.
If the width and height attributes are omitted, the default drawing surface is 300 pixels wide and 150 pixels high.
No. Canvas is useful for pixel-based and frequently redrawn graphics. SVG is often better for scalable vector graphics, while normal HTML should be used for semantic text, links, forms and page structure.
fillRect() | moveTo() | lineTo() | arc() | setLineDash() | fillStyle
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.