HTML Canvas Tutorial: Drawing with <canvas> and JavaScript

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

Basic HTML Canvas example Top ↑

<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>
A blue rectangle drawn on an HTML canvas.

Canvas width, height and coordinate system Top ↑

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.

  • X = 0, Y = 0 is the top-left corner.
  • The width and height HTML attributes define the drawing surface dimensions. If omitted, the default canvas size is 300 by 150.
  • Use CSS to control how the element fits the page, but do not rely on CSS width and height alone to define the drawing buffer because scaling can distort or blur the drawing.
  • Changing the canvas width or height after drawing resets the drawing surface and the rendering state.

Getting the 2D drawing context Top ↑

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.

Adding a visible border around the canvas Top ↑

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>

Drawing lines and paths Top ↑

Line drawn on an HTML 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 APIPurpose
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.
lineWidthSets the width used for stroked lines.
lineCapControls the shape of line ends.
lineJoinControls how connected line segments join.
miterLimitLimits long miter joins.
setLineDash()Sets a repeating dash-and-gap pattern.
lineDashOffsetShifts the starting position of a dash pattern.
closePath()Adds a path segment back toward the start of the current subpath.
strokeStyleSets the color, gradient or pattern used for strokes.

Try the line drawing demo | Marching ants dashed-border animation

Drawing rectangles Top ↑

Rectangle drawn on an HTML canvas
Canvas APIPurpose
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.

Try the rectangle demo

Drawing arcs, circles and curves Top ↑

Arc and circle drawn on an HTML canvas
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 APIPurpose
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

Adding text to Canvas Top ↑

Canvas APIPurpose
fontSets the font style, size and family.
fillText()Draws filled text at the specified coordinates.
strokeText()Draws the outline of text.
textAlignControls horizontal text alignment.
textBaselineControls how text aligns vertically to the Y coordinate.

Try the Canvas text demo

Colors, fills and gradients Top ↑

Canvas APIPurpose
fillStyleSets the color, gradient or pattern used for fills.
createLinearGradient()Creates a gradient along a straight line.
createRadialGradient()Creates a gradient using two circles.

Adding shadows Top ↑

Canvas propertyPurpose
shadowColorSets the shadow color.
shadowOffsetXMoves the shadow horizontally.
shadowOffsetYMoves the shadow vertically.
shadowBlurSets the shadow blur level.

Canvas shadow demo | Interactive shadow demo

Rotate, translate and transform Canvas drawings Top ↑

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

Canvas graphs, curves and practical projects Top ↑

After learning the drawing primitives, these existing examples show how they can be combined into larger graphics:

Mouse and pointer interaction Top ↑

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.

Do you need jQuery for Canvas? Top ↑

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.

Canvas accessibility Top ↑

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.

  • Provide useful fallback content between the opening and closing <canvas> tags when appropriate.
  • For charts and data visualizations, provide the important values or conclusions in accessible HTML as well.
  • For interactive Canvas applications, provide keyboard-operable controls and an accessible alternative for essential tasks.
  • Use meaningful nearby text when a drawing communicates information the reader needs to understand.

Common Canvas mistakes Top ↑

  • Trying to draw with HTML alone. The <canvas> element creates the surface; JavaScript performs the drawing.
  • Setting only CSS dimensions and unintentionally stretching the bitmap.
  • Forgetting beginPath() when starting an independent path and accidentally connecting shapes.
  • Calling path-building methods such as lineTo() but forgetting stroke() or fill().
  • Using Canvas for ordinary page text or controls that should be semantic HTML.
  • Assuming pixels drawn on Canvas become searchable DOM elements.

Frequently asked questions Top ↑

What is the HTML Canvas element used for? Top ↑

It provides a drawing surface that scripts can use for 2D graphics, charts, games, animations, image processing and other pixel-based graphics.

Does Canvas require JavaScript? Top ↑

For normal dynamic drawing, yes. HTML creates the canvas element, while JavaScript calls the Canvas API to draw into it.

What does getContext('2d') do? Top ↑

It requests the canvas 2D rendering context. That object provides the methods and properties used to draw shapes, paths, text and images.

What are the default Canvas dimensions? Top ↑

If the width and height attributes are omitted, the default drawing surface is 300 pixels wide and 150 pixels high.

Is Canvas a replacement for SVG or normal HTML? Top ↑

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





plus2net.com










We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2026   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer