Canvas coordinate system
Canvas drawing uses a coordinate system whose origin (0, 0) is at the top-left corner.
What you will learn
- How x and y coordinates locate a point
- Why positive x moves right and positive y moves down
- How canvas size and rectangle arguments work together
The basic rule
xincreases as a point moves right.yincreases as a point moves down.(0, 0)is the top-left of the drawing area.
// x = 20, y = 10, width = 120, height = 60
context.fillRect(20, 10, 120, 60);The rectangle starts 20 pixels from the left and 10 pixels from the top. Its right edge is at x 140, and its bottom edge is at y 70.
Canvas size matters
The width and height attributes define the drawing buffer. CSS can change how that buffer is displayed, but stretching it without considering the ratio can make the drawing blurry or distorted.
Common mistakes
- Do not treat the center of the canvas as
(0, 0). - Remember that y does not increase upward as it does in some mathematics diagrams.
- Keep drawing coordinates within the canvas when you want the complete shape to be visible.