HTML5 Canvas
HTML5's <canvas> element provides a powerful way to dynamically draw graphics using JavaScript. You can think of it as a "canvas" where you can draw lines, shapes, text, images, and anything else.
<canvas> itself is just a graphics container; you must use JavaScript scripts to complete the actual drawing tasks. It's widely used in data visualization, image editors, game development, and more.
Creating a Canvas
First, place a <canvas> element in HTML and give it an id for reference in scripts, along with width and height.
Drawing with JavaScript
All drawing operations are done in JavaScript.
- Get the Canvas element: Use
document.getElementById()to get the<canvas>element. - Get the 2D rendering context: Call the element's
getContext('2d')method. This method returns an object with all drawing methods and properties. - Start drawing: Use the context object to perform drawing operations.
Drawing a Rectangle
Drawing a Line
Drawing paths (like lines) typically follows these steps:
beginPath(): Start a new path.moveTo(x, y): Move the pen to the specified coordinates as the starting point of the path.lineTo(x, y): Add a straight line from the current position to the specified coordinates.stroke(): Actually draw the path outline.
Drawing a Circle
Use the arc(x, y, radius, startAngle, endAngle) method to draw circles or arcs.
Canvas vs. SVG
HTML5 also provides another graphics technology: SVG. Their main differences are:
-
Canvas:
- Pixel-based (bitmap).
- Drawn via JavaScript, it's a "draw and forget" mode that doesn't keep references to graphic objects.
- Gets distorted when enlarged.
- Suitable for pixel-level image processing, dynamic rendering, and games.
-
SVG (Scalable Vector Graphics):
- XML-based vector graphics.
- Each shape is a DOM element that can be manipulated via CSS and JS.
- Scales infinitely without distortion.
- Suitable for high-quality, interactive charts, icons, and maps.