Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to draw grid using HTML5 and canvas or SVG?
HTML5 provides two powerful ways to create grid patterns: Canvas and SVG. Both offer different advantages depending on your needs.
Drawing Grid Using HTML5 Canvas
Canvas provides a pixel-based approach for drawing grids programmatically. Here's how to create a basic grid:
<canvas id="gridCanvas" width="300" height="300"></canvas>
<script>
// Get canvas and context
const canvas = document.getElementById('gridCanvas');
const ctx = canvas.getContext('2d');
// Grid settings
const gridSize = 20; // Size of each grid cell
const canvasWidth = canvas.width;
const canvasHeight = canvas.height;
// Set line style
ctx.strokeStyle = '#ddd';
ctx.lineWidth = 1;
// Draw vertical lines
for (let x = 0; x
Drawing Grid Using SVG
SVG offers a more declarative approach with built-in pattern support:
<svg width="300" height="300" xmlns="http://www.w3.org/2000/svg">
<defs>
<pattern id="grid" width="20" height="20" patternUnits="userSpaceOnUse">
<path d="M 20 0 L 0 0 0 20" fill="none" stroke="#ddd" stroke-width="1"/>
</pattern>
</defs>
<rect width="100%" height="100%" fill="url(#grid)" />
</svg>
Interactive Canvas Grid Example
Here's a more complete example with customizable grid properties:
<canvas id="interactiveGrid" width="400" height="300"></canvas>
<script>
function drawGrid(canvasId, cellSize = 25, lineColor = '#ccc') {
const canvas = document.getElementById(canvasId);
const ctx = canvas.getContext('2d');
// Clear canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Set line style
ctx.strokeStyle = lineColor;
ctx.lineWidth = 1;
// Draw grid
ctx.beginPath();
// Vertical lines
for (let x = 0; x
Comparison
| Feature | Canvas | SVG |
|---|---|---|
| Performance | Better for complex animations | Better for simple static grids |
| Scalability | Pixel-based (can be blurry) | Vector-based (always crisp) |
| Interactivity | Manual event handling | Built-in DOM events |
| File Size | Smaller for complex scenes | Smaller for simple graphics |
Key Points
- Add 0.5 to coordinates in Canvas for crisp 1px lines
- Use SVG patterns for repeating grid designs
- Canvas is better for dynamic, pixel-based graphics
- SVG is ideal for scalable, resolution-independent grids
Conclusion
Choose Canvas for interactive applications requiring frequent updates, and SVG for static grids that need to scale perfectly. Both methods provide excellent grid-drawing capabilities with their own strengths.
Advertisements
