Canvas
The Canvas API is also a part of the Web APIs. It allows for dynamic, scriptable rendering of 2D shapes and bitmap images.
It provides a drawing surface where you can create graphics on the fly using JavaScript. With the Canvas API, you can draw shapes, text, and images, as well as manipulate pixels directly. This makes it ideal for applications like games, animations, and data visualizations.
The API is accessible through the <canvas> HTML element:
<!DOCTYPE html>
<html>
<head>
<title>Canvas</title>
</head>
<body>
<canvas id="canvas" width="300" height="250"></canvas>
<script src="script.js"></script>
</body>
</html>
In script.js:
const canvas = document.getElementById('canvas')
const ctx = canvas.getContext('2d')
ctx.fillStyle = 'blue'
ctx.fillRect(50, 50, 150, 100)
Canvas vs SVG
SVG (Scalable Vector Graphics) represents graphics as DOM elements. This allows you to leverage standard HTML event handling, making it easier to manage user interactions like clicks, hovers, and other events.
On the other hand, Canvas is a bitmap-based approach where you draw pixels directly, meaning you need to handle interaction and collision detection manually. While libraries like PixiJS can streamline this process, it often requires more setup compared to the straightforward integration of SVG with the HTML structure.
If interactivity and ease of integration are your primary concerns, SVG might be the better choice. For performance-intensive applications, or games, Canvas could be advantageous.