HTML5 Canvas & SVG Basics
HTML5 provides two main ways to draw shapes and graphics in the browser: the raster-based Canvas element and vector-based SVG elements.
1 Canvas (Raster) vs. SVG (Vector)
Canvas and SVG are suited for different use cases:
- <canvas>: A raster-based grid. Drawn dynamically using JavaScript, making it excellent for rendering games, charts, or heavy pixel manipulations.
- <svg>: A XML vector format. Stays sharp at any scale, behaves like standard DOM nodes, and can be styled easily with CSS.
2 Graphic Elements Code
Let's check inline SVG vector graphics:
HTML — Vector Shape (SVG)
<!-- Clean inline vector graphic shape -->
<svg width="100" height="100" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
<circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
</svg>
<!-- Canvas element -->
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000;"></canvas>
3 Code Challenge
Challenge: Write an inline SVG drawing a rectangle shape using the `<rect>` element. Specify width, height, fill colors, and test its display in your browser.