Content: Introduction to Canvas, basic drawing APIs, and style settings
Canvas Coordinate System
The canvas coordinate system has its origin at the top-left corner, with the following rules:
- The positive x-direction is to the right.
- The positive y-direction is down.

Basic Steps for Drawing on Canvas
1 | // Get the canvas element |
Canvas Width and Height
By default, a canvas has a width of 300 pixels and a height of 150 pixels. You can set the canvas width and height using the HTML attributes, and you cannot use CSS to set these dimensions.
1 | <canvas id="canvas" width="600" height="400" style="border:1px solid #ccc"></canvas> |
1 | var canvas = document.getElementById("canvas"); |
Basic Drawing APIs in Canvas
| Simple API | Description |
|---|---|
| moveTo(x, y) | Set the starting point |
| lineTo(x, y) | Draw a path |
| stroke() | Stroke the path |
| fill() | Fill the path |
| stroke() and fill() | Both stroke and fill |
| beginPath() | Start a new path |
| closePath() | Close the path |
Stroke and Fill
stroke(): Draw the outline of a path.fill(): Fill the area enclosed by a path.stroke()andfill(): Both stroke and fill the path.
1 | var canvas = document.getElementById("canvas"); |
Style Settings in Canvas
| Style API | Description |
|---|---|
| strokeStyle | Stroke color |
| fillStyle | Fill color |
| lineWidth | Line width |
| lineCap | Line cap style (butt, round, square) |
| lineJoin | Line join style (miter, round, bevel) |
| setLineDash() | Set line dash pattern |
| getLineDash() | Get line dash pattern |
| lineDashOffset | Set line dash offset (negative values move to the right) |
Line Width, Stroke Color, and Fill Color
1 | var canvas = document.getElementById("canvas"); |
getLineDash() to Get the Line Dash Pattern
lineDashOffset for Line Dash Offset
A positive value moves the line dash pattern to the left, while a negative value moves it to the right.
Other Drawing Techniques in Canvas
Drawing Curves
To draw curves on a canvas, you can draw a series of points that follow the curve’s equation.
1 | var canvas = document.getElementById("canvas"); |
Gradient Fill
To create gradient effects, draw one point at a time and change the color attribute.
1 | var canvas = document.getElementById("canvas"); |