Master HTML5 Canvas: Draw Shapes, Lines, Circles, and Images Step‑by‑Step
This guide explains the fundamentals of HTML5 Canvas, covering how to obtain the canvas and its context, draw rectangles, lines, circles, clear the canvas, and manipulate images with drawImage and clipping, all illustrated with clear examples and code snippets.
1. What is Canvas?
HTML5 introduced the canvas element, a core technology for drawing graphics and creating animations using JavaScript.
2. Basic Usage
Drawing with canvas involves three steps:
Obtain the canvas element.
Get the 2D rendering context ( context).
Use the context to draw shapes.
2.1 Draw a Rectangle
Set fillStyle (color, gradient, or pattern) before calling fillRect() or strokeRect(). Define the canvas width and height as HTML attributes, not CSS, to ensure correct dimensions.
2.2 Draw Lines
Use moveTo(x, y) and lineTo(x, y) to create straight lines. The canvas uses the W3C coordinate system where the y‑axis points downwards. Repeating lineTo() allows drawing multiple connected segments, triangles, arrows, and other polygons.
2.3 Draw a Circle
Use arc(x, y, radius, startAngle, endAngle, anticlockwise). Call beginPath() before and closePath() after drawing. Angles are in radians (e.g., 180° = Math.PI), and anticlockwise determines the drawing direction.
2.4 Clear the Canvas
Use clearRect(x, y, width, height) to erase a rectangular area. To clear the entire canvas, set width and height to the canvas’s own dimensions.
3. Image Operations
3.1 Draw an Image
Use drawImage(image, dx, dy, dw, dh) where image is a loaded HTMLImageElement, and dx, dy, dw, dh specify the destination position and size. The image must be fully loaded before drawing.
3.2 Clip an Image
First draw a basic shape (rectangle, polygon, or circle), then call clip() to restrict subsequent drawing to that shape. Finally, draw the image; only the portion inside the clipping region will appear.
This article covers the basic features of the canvas element; advanced topics such as collision detection, complex animations, and chart libraries will be explored in future tutorials.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaoDou Frontend Team
Open-source, innovative, collaborative, win‑win – sharing frontend tech and shaping its future.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
