To start drawing 20 figures with HTML canvas, you must first create the canvas element and get the 2D context; 1. Add a
The HTML <canvas></canvas>
element is a powerful tool for rendering dynamic 2D graphics directly in the browser using JavaScript. Unlike SVG or CSS-based graphics, canvas operates as a bitmap—once something is drawn, it's just pixels. This makes it ideal for games, data visualizations, animations, and real-time rendering.

Here's a practical guide to getting started with the canvas element for 20 graphics.
Setting Up the Canvas Element
To begin, you need to add a <canvas></canvas>
tag to your HTML. It acts as a container for graphics, but by itself, it does nothing.

<canvas id="myCanvas" width="500" style="max-width:90%"></canvas>
You should always set width
and height
attributes directly on the canvas (not via CSS) to avoid scaling issues. CSS can stretch the canvas, leading to blurry graphics.
After placing the canvas, access it in JavaScript and get the 2D drawing context:

const canvas = document.getElementById('myCanvas'); const ctx = canvas.getContext('2d');
The ctx
object is your main tool for drawing shapes, text, images, and more.
Drawing Basic Shapes
With the 2D context, you can draw rectangles, paths, circles, and lines.
Rectangles
Canvas has built-in methods for rectangles:
-
fillRect(x, y, width, height)
– draws a filled rectangle -
strokeRect(x, y, width, height)
– draws an outlined rectangle -
clearRect(x, y, width, height)
– clears a rectangular area
Example:
ctx.fillStyle = 'blue'; ctx.fillRect(10, 10, 100, 50); ctx.strokeStyle = 'red'; ctx.lineWidth = 3; ctx.strokeRect(120, 10, 100, 50);
Paths and Lines
For custom shapes, use paths:
ctx.beginPath(); ctx.moveTo(200, 20); // Start point ctx.lineTo(250, 80); // Draw line to ctx.lineTo(150, 80); ctx.closePath(); // Connect back to start ctx.fillStyle = 'green'; ctx.fill();
This draws a filled triangle.
Circles and Arcs
Use arc()
to draw circles or parts of circles:
ctx.beginPath(); ctx.arc(100, 100, 50, 0, Math.PI * 2); // x, y, radius, startAngle, endAngle ctx.fillStyle = 'purple'; ctx.fill();
You can create pie charts, clocks, or custom curves by adjusting the angles.
Styling and Colors
Canvas lets you control how shapes look:
-
fillStyle
– sets color, gradient, or pattern for fills -
strokeStyle
– same, but for outlines -
lineWidth
,lineCap
,lineJoin
– control line appearance
Examples:
ctx.fillStyle = '#FF5733'; ctx.strokeStyle = 'rgba(0, 0, 255, 0.5)'; ctx.lineWidth = 4; ctx.lineCap = 'round'; // 'butt', 'round', or 'square'
You can also use gradients:
const gradient = ctx.createLinearGradient(0, 0, 200, 0); gradient.addColorStop(0, 'yellow'); gradient.addColorStop(1, 'red'); ctx.fillStyle = gradient; ctx.fillRect(10, 130, 200, 60);
Drawing Text and Images
Text
Canvas supports text rendering with control over font, alignment, and style:
ctx.font = '20px Arial'; ctx.fillStyle = 'black'; ctx.fillText('Hello Canvas', 10, 170); ctx.strokeText('Outline Text', 10, 200);
Use textAlign
( start
, end
, center
, left
, right
) and textBaseline
( top
, middle
, bottom
) for precision placement.
Images
You can draw images from <img alt="A Guide to the HTML Canvas Element for 2D Graphics" >
elements or other sources:
const img = new Image(); img.src = 'picture.jpg'; img.onload = () => { ctx.drawImage(img, 0, 0, 150, 100); // image, x, y, width, height };
drawImage()
is versatile—it can also slice and scale parts of images.
Animation Basics
Canvas shines with animation. To animate, you typically:
- Clear the canvas
- Update object positions
- Redraw everything
- Repeat using
requestAnimationFrame
Example: Moving circle
let x = 0; function animate() { ctx.clearRect(0, 0, canvas.width, canvas.height); // Clear ctx.beginPath(); ctx.arc(x, 150, 20, 0, Math.PI * 2); ctx.fillStyle = 'orange'; ctx.fill(); x = 2; if (x > canvas.width) x = 0; requestAnimationFrame(animate); } animate();
This loop creates smooth motion by syncing with the browser's refresh rate.
Performance Tips and Best Practices
- Avoid unnecessary redraws : Only redraw what changed, or use multiple canvases (eg, one for background, one for moving objects).
- Cache complex drawings : If a shape doesn't change, draw it once offscreen and reuse with
drawImage()
. - Limit
getImageData
/putImageData
: These are slow; use sparingly for pixel manipulation. - Use
requestAnimationFrame
instead ofsetInterval
for smoother, efficient animation.
Canvas gives you full control over 2D rendering. While it lacks built-in object management (you're drawing pixels, not DOM elements), that same low-level access enables high-performance visuals. With practice, you can build anything from charts to games.
Basically, start small—draw a shape, add color, animate it—and build up from there.
The above is the detailed content of A Guide to the HTML Canvas Element for 2D Graphics. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

ARIAattributesenhancewebaccessibilityforuserswithdisabilitiesbyprovidingadditionalsemanticinformationtoassistivetechnologies.TheyareneededbecausemodernJavaScript-heavycomponentsoftenlackthebuilt-inaccessibilityfeaturesofnativeHTMLelements,andARIAfill

React itself does not directly manage focus or accessibility, but provides tools to effectively deal with these issues. 1. Use Refs to programmatically manage focus, such as setting element focus through useRef; 2. Use ARIA attributes to improve accessibility, such as defining the structure and state of tab components; 3. Pay attention to keyboard navigation to ensure that the focus logic in components such as modal boxes is clear; 4. Try to use native HTML elements to reduce the workload and error risk of custom implementation; 5. React assists accessibility by controlling the DOM and adding ARIA attributes, but the correct use still depends on developers.

Let’s talk about the key points directly: Merging resources, reducing dependencies, and utilizing caches are the core methods to reduce HTTP requests. 1. Merge CSS and JavaScript files, merge files in the production environment through building tools, and retain the development modular structure; 2. Use picture Sprite or inline Base64 pictures to reduce the number of image requests, which is suitable for static small icons; 3. Set browser caching strategy, and accelerate resource loading with CDN to speed up resource loading, improve access speed and disperse server pressure; 4. Delay loading non-critical resources, such as using loading="lazy" or asynchronous loading scripts, reduce initial requests, and be careful not to affect user experience. These methods can significantly optimize web page loading performance, especially on mobile or poor network

Shallowrenderingtestsacomponentinisolation,withoutchildren,whilefullrenderingincludesallchildcomponents.Shallowrenderingisgoodfortestingacomponent’sownlogicandmarkup,offeringfasterexecutionandisolationfromchildbehavior,butlacksfulllifecycleandDOMinte

StrictMode does not render any visual content in React, but it is very useful during development. Its main function is to help developers identify potential problems, especially those that may cause bugs or unexpected behavior in complex applications. Specifically, it flags unsafe lifecycle methods, recognizes side effects in render functions, and warns about the use of old string refAPI. In addition, it can expose these side effects by intentionally repeating calls to certain functions, thereby prompting developers to move related operations to appropriate locations, such as the useEffect hook. At the same time, it encourages the use of newer ref methods such as useRef or callback ref instead of string ref. To use Stri effectively

Create TypeScript-enabled projects using VueCLI or Vite, which can be quickly initialized through interactive selection features or using templates. Use tags in components to implement type inference with defineComponent, and it is recommended to explicitly declare props and emits types, and use interface or type to define complex structures. It is recommended to explicitly label types when using ref and reactive in setup functions to improve code maintainability and collaboration efficiency.

There are three key points to be mastered when processing Vue forms: 1. Use v-model to achieve two-way binding and synchronize form data; 2. Implement verification logic to ensure input compliance; 3. Control the submission behavior and process requests and status feedback. In Vue, form elements such as input boxes, check boxes, etc. can be bound to data attributes through v-model, such as automatically synchronizing user input; for multiple selection scenarios of check boxes, the binding field should be initialized into an array to correctly store multiple selected values. Form verification can be implemented through custom functions or third-party libraries. Common practices include checking whether the field is empty, using a regular verification format, and displaying prompt information when errors are wrong; for example, writing a validateForm method to return the error message object of each field. You should use it when submitting

Server-siderendering(SSR)inNext.jsgeneratesHTMLontheserverforeachrequest,improvingperformanceandSEO.1.SSRisidealfordynamiccontentthatchangesfrequently,suchasuserdashboards.2.ItusesgetServerSidePropstofetchdataperrequestandpassittothecomponent.3.UseSS
