Introduction
In the realm of web graphics, two powerful technologies stand out: HTML Canvas and SVG (Scalable Vector Graphics). Both are essential for creating dynamic and interactive visuals on the web, but they cater to different needs and scenarios.
Earlier, I used to think that whats the use of the Canvas API when we have SVG which is light-weight, more scalable and easy to use. But once I started exploring the Canvas API, my opinion got changed with this just one example on MDN.
In this article, we will delve into the world of HTML Canvas, highlight key differences and similarities between Canvas and SVG, and provide guidance on when to choose one over the other. Additionally, we'll demonstrate Canvas's capabilities through hands-on code examples, showcasing its practical applications in real-world scenarios. Whether you're a developer looking to enhance your web graphics skills or just curious about these technologies, this article will provide valuable insights and practical knowledge.
Differences and Similarities: Canvas vs. SVG
Canvas is based on pixels. HTML Canvas is a bitmap, pixel-based graphics system. When you draw on a canvas, you are manipulating individual pixels directly. It's like working on a pristine canvas, where every stroke of paint influences certain parts and becomes hard to change once placed.
SVG is a markup language based on XML for describing two-dimensional vector graphics. Unlike Canvas, SVG retains information about the objects and shapes drawn, treating each element as part of a document tree (DOM) and can be manipulated through CSS and JavaScript.
Illustration to understand the difference between Pixels(Canvas) and Vectors(SVG)
Rendering Method:
Canvas uses immediate mode graphics, meaning the drawing is done pixel by pixel directly on the canvas, and once drawn, the output is fixed unless explicitly updated.
SVG, on the other hand, is a retained mode graphics system, where each element is part of the Document Object Model (DOM) and can be manipulated through CSS and JavaScript.Performance:
Canvas is ideal for rendering complex and dynamic graphics where performance is crucial, such as in game development or real-time data visualization.
SVG excels with vector-based graphics that require scalability and high quality at any resolution, making it perfect for logos, icons, and illustrations.Interactivity:
SVG elements are inherently interactive as part of the DOM, allowing for easy event handling.
Canvas requires manual coding for interaction, adding complexity to the development process.File Size:
SVG files are typically smaller for simple, vector-based graphics as they use mathematical descriptions for shapes. For eg: Icons and Logos, Illustrations
Canvas drawings can result in smaller file sizes, especially for complex scenes, since they do not retain any drawing commands after rendering. For eg: Digital paintings
File Size | SVG | Canvas |
Simple Graphics | Smaller: SVG is efficient for simple vector shapes like icons and logos. Example: A basic SVG logo with a few shapes and text is usually just a few KBs. | Larger: The same simple graphic rendered on Canvas will be larger due to pixel data storage. Example: A Canvas image with the same logo might be larger even though it’s simple. |
Complex Graphics | Larger: Complex SVG files with many shapes and detailed paths can be quite large. Example: An detailed SVG infographic with numerous data points can be several hundred KBs. | Smaller: Canvas can handle complex scenes more efficiently as it stores rendered pixel data. Example: A high-resolution, detailed game scene on Canvas might be smaller compared to the equivalent SVG file. |
Photographs | Larger: SVG is not suitable for complex photographs due to file size constraints. Example: Converting a photograph to SVG is impractical and results in a massive file. | Smaller: Canvas handles photographs efficiently with pixel-based storage. Example: A high-resolution photograph rendered on Canvas can be relatively small, especially when saved in a compressed format like JPEG. |
File Size for Detailed Textures | Larger: SVG is not ideal for detailed textures or gradients as it can become cumbersome. Example: A highly textured SVG background may become quite large. | Smaller: Detailed textures and gradients are more efficiently handled by Canvas. Example: A complex texture in a Canvas drawing might be smaller compared to a detailed SVG texture. |
In short, the choice between SVG and Canvas largely depends on the complexity of the graphics and shapes being used. The table above provides a guide to help you decide which format to use in different scenarios. To illustrate these differences further, let’s examine actual comparisons by converting SVG to JPEG and JPEG to SVG.
Use Cases: When to Use Which?
When deciding between Canvas and SVG, consider the following scenarios:
Use Canvas for:
High-performance games and animations
Real-time data visualizations
Applications requiring pixel manipulation
Use SVG for:
Graphics that need to be scalable and maintain high quality
Interactive and detailed illustrations
Responsive design elements that adjust with screen size
In sum, the overhead of DOM rendering is more poignant when juggling hundreds if not thousands of objects; in this scenario, Canvas is the clear winner. However, both the canvas and SVG are invariant to object sizes. Given the final tally, the canvas offers a clear win in performance
Alvin Wan
Code Differences: Canvas vs. SVG
Basic examples
Draw Line using Line Algorithm with Canvas API - View Demo | View Code
Draw circle using pixels - Canvas API - View Demo | View Code
Draw 2D Polygon using circle equations - Canvas API - View Demo | View Code
Draw 3D Polygon using circle equations - Canvas API - View Demo | View Code
Real world Use Cases - Canvas
Google Sheet: Efficient for large datasets and rapid updates
Google Map: Smooth scrolling and zooming capabilities
Figma: Rendering complex visuals with minimal DOM elements
Image Processing: Batch rendering updates for performance
Google Sheets, along with other web-based spreadsheet applications, often uses the Canvas API for several reasons, particularly related to performance and flexibility in rendering complex and interactive user interfaces.
Here’s a detailed explanation of why Google Sheets might use Canvas
Performance & Efficient Rendering: The Canvas API allows for efficient pixel-based rendering, which is crucial for applications like Google Sheets that need to handle large datasets and rapid updates. Redrawing only the parts of the screen that change improves performance.
Smooth Scrolling and Zooming: Canvas can handle smooth scrolling and zooming of the spreadsheet interface, ensuring that large sheets with many rows and columns remain responsive.
Complex Visuals: With Canvas, it's easier to render complex visuals, such as conditional formatting, sparklines, and intricate cell borders, without relying on a plethora of DOM elements.
Minimized DOM Size: Using Canvas reduces the number of DOM elements, which can become unwieldy and slow when dealing with large tables. A leaner DOM improves overall performance and responsiveness.
Batch Updates: The Canvas API allows for batch rendering updates, meaning multiple changes can be drawn in a single frame, reducing the overhead of updating the DOM multiple times.
You can see, the power of Canvas api that can power tools like Google Sheet and Figma. But you may wonder, how tools like Google Sheet manage interactivity with Canvas API?
First look at this example google-sheet-grid.html
. Here, we are identifying the selected cell by applying some calculations based on height and width of the cell and the coordinates of the area where mouse pointer is clicked. Once you know the cell index, you can use it to store data.
function handleMouseClick(evt) {
const row = Math.floor(evt.clientY / cellHeight);
const col = Math.floor(evt.clientX / cellWidth);
highlightCell(row, col);
setData(row, col)
drawGrid();
}
function setData(row, col) {
if (!data[`${row}-${col}`]) {
data[`${row}-${col}`] = 0;
}
if (typeof data[`${row}-${col}`] === 'number') {
data[`${row}-${col}`] += 1;
}
}
Real world Use Cases - SVG
Icons: Interactivity and easy scaling without burdening page performance.
Interactive Maps: Scalability, zooming, and native event handling.
Interactive Charts: Data-driven visualizations with CSS and JavaScript animations.
SVG is an excellent option for icons, offering interactivity and easy scaling without burdening page performance, thanks to its compact size.
Here’s a detailed explanation of why we might use SVG for Icons, Charts and Maps
Scalability: SVG is vector-based, meaning it uses mathematical equations to draw shapes. This ensures that the map maintains high quality and sharpness at any scale.
Zooming: SVG can be zoomed in and out without losing quality or detail, making them ideal for applications where users need to explore different levels of detail.
Interactivity Event Handling: SVG supports native DOM event handling, allowing you to easily add interactive features such as tooltips, popups, and custom behaviors on clicks, hovers, and other user interactions.
Animation: SVG elements can be animated using CSS and JavaScript, enabling dynamic visual effects like highlighting regions, animating transitions, and more.
Styling CSS Styling: SVG elements can be styled using CSS, which allows for easy customization and theming.
DOM Manipulation: SVG elements are part of the DOM, allowing you to manipulate them using JavaScript libraries like D3.js. This integration makes it easy to bind data to elements and create data-driven visualizations.
Transforms: You can apply transformations (e.g., scaling, rotating, translating) to SVG elements, providing fine-grained control over how elements are displayed and interacted with.
Export and Import: SVG files can be easily exported and imported making it convenient for designers and developers to collaborate.
Performance: For maps with a moderate number of elements, SVG performs well in modern browsers. The rendering is typically efficient for interactive applications that require frequent updates.
Accessibility: SVG supports text elements that can be styled and positioned precisely, making it easier to add labels and descriptions. This also improves accessibility for users who rely on screen readers.
Interactive SVG Map - Highlighting a specific country
Interactive SVG Map - Highlighting a area-wise winner of the general elections
Conclusion
We have explored several scenarios where the advantages of using SVG and Canvas become apparent. Each technology has its unique strengths. By carefully considering the needs of your project, you can make informed decisions about when to use SVG, Canvas, or a combination of both.
Showcasing My Canvas Examples
Google Sheet example using Canvas with interactivity - View Demo | View Code
Render Image - read and process image data - View Demo | View Code
If you want to see what more we can do with the Canvas API, check this youtube channel @Frankslaboratory
References:
https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Manipulating_video_using_canvas
https://css-tricks.com/when-to-use-svg-vs-when-to-use-canvas/
https://medium.com/stackanatomy/svg-vs-canvas-a-comparison-1b58e6c84326
https://www.madebymike.com.au/writing/canvas-image-manipulation/
https://codepen.io/jakealbaugh/post/canvas-image-pixel-manipulation