HTML5 Canvas and SVG are both standards-based HTML5 technologies that you can use to create amazing graphics and visual experiences. The question I’m asking in this article is the following: Should it matter which one you use in your project? In other words, are there any use cases for preferring HTML5 Canvas over SVG?
First, let’s spend a few words introducing HTML5 Canvas and SVG.
What Is HTML5 Canvas?
Here’s how the WHATWG specification introduces the
canvaselement provides scripts with a resolution-dependent bitmap canvas, which can be used for rendering graphs, game graphics, art, or other visual images on the fly.
In other words, the
Here’s a basic code sample:
<canvas id="myCanvas" width="800" height="800"></canvas>
const canvas = document.getElementById('myCanvas'); const context = canvas.getContext('2d'); context.fillStyle = '#c00'; context.fillRect(10, 10, 100, 100);
You can take advantage of the HTML5 Canvas API methods and properties by getting a reference to the 2D context object. In the example above, I’ve drawn a simple red square, 100 x 100 pixels in size, placed 10px from the left and 10px from the top of the
<canvas> drawing surface.
Being resolution-dependent, images you create on
<canvas> may lose quality when enlarged or displayed on Retina Displays.
Drawing simple shapes is just the tip of the iceberg. The HTML5 Canvas API allows you to draw arcs, paths, text, gradients, etc. You can also manipulate your images pixel by pixel. This means that you can replace one color with another in certain areas of the graphics, you can animate your drawings, and even draw a video onto the canvas and change its appearance.
What Is SVG?
SVG stands for Scalable Vector Graphics. According to the specification:
SVG is a language for describing two-dimensional graphics. As a standalone format or when mixed with other XML, it uses the XML syntax. When mixed with HTML5, it uses the HTML5 syntax. …
SVG drawings can be interactive and dynamic. Animations can be defined and triggered either declaratively (i.e., by embedding SVG animation elements in SVG content) or via scripting.
SVG is an XML file format designed to create vector graphics. Being scalable has the advantage of letting you increase or decrease a vector image while maintaining its crispness and high quality. (This can’t be done with HTML5 Canvas-generated images.)
Here’s the same red square (previously created with HTML5 Canvas) this time drawn using SVG:
<svg xmlns="https://www.w3.org/2000/svg" viewbox="0 0 600 600"> <desc>Red rectangle shape</desc> <rect x="10" y="10" width="100" height="100" fill="#c00" /> </svg>
<div>. As it will become clearer in the following sections, this difference plays a significant part when you need to make a choice between Canvas and SVG for your next project.
Immediate Mode and Retained Mode
Immediate mode means that, once your drawing is on the canvas, the canvas stops keeping track of it. In other words you, as the developer, you need to work out the commands to draw objects, create and maintain the model or scene of what the final output should look like, and specify what needs to be updated. The browser’s Graphics API simply communicates your drawing commands to the browser, which then executes them.
SVG uses the retained approach, where you simply issue your drawing instructions of what you want to display on the screen, and the browser’s Graphics API creates an in-memory model or scene of the final output and translates it into drawing commands for your browser.
Being an immediate graphics system, Canvas hasn’t got a DOM, or Document Object Model. With Canvas, you draw your pixels and the system forgets all about them, thereby cutting down on the extra memory needed to maintain an internal model of your drawing. With SVG, each object you draw gets added to the browser’s internal model, which makes your life as a developer somewhat easier, but at some costs in terms of performance.
On the basis of the distinction between immediate and retained mode, as well as other specific characteristics of Canvas and SVG respectively, it’s possible to outline some cases where using one technology over the other might better serve your project’s goals.
HTML5 Canvas: Pros and Cons
The HTML5 Canvas specification clearly recommends that authors should not use the
<canvas> element where they have other more suitable means available to them.
For instance, for a graphically rich
<header> element, the best tools are HTML and CSS, not
<canvas> (and neither is SVG, by the way). Dr Abstract, creator and founder of the Zim JS canvas framework, confirms this view as he writes:
So, that’s a clear-cut example of when not to use
<canvas>. But when is
<canvas> a good option?
This tweet by Sarah Drasner summarizes some major pros and cons of canvas features and capabilities, which can help us to work out some use cases for this powerful technology:
I had this slide in a lot of talks and workshops over the years: pic.twitter.com/4K0C7mNzg2
— Sarah Drasner (@sarah_edo) October 2, 2019
You can view the image from the tweet here.
What HTML5 Canvas Can Be Great For
Alvin Wan has benchmarked Canvas and SVG in terms of performance both in relation to the number of objects being drawn and in relation to the size of the objects or the canvas itself. He states his results as follows:
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.
Drawing on what we know about Canvas, especially its excellent performance at drawing lots of objects, here are some possible scenarios where it might be appropriate, and even preferable to SVG.
Games and Generative Art
For graphics-intensive, highly interactive games, as well as for generative art, Canvas is generally the way to go.
Ray tracing is a technique for creating 3D graphics.
Ray tracing can be used to hydrate an image by tracing the path of light through pixels in an image plane and simulating the effects of its encounters with virtual objects. … The effects achieved by ray tracing, … range from … creating realistic images from otherwise simple vector graphics to applying photo-like filters to remove red-eye. — SVG vs Canvas: how to choose, Microsoft Docs.
If you’re curious, here’s a raytracer application in action by Mark Webster.
However, although HTML5 Canvas is definitely better suited to the task than SVG could ever be, it doesn’t necessarily follow that ray tracing is best executed on a
<canvas> element. In fact, the strain on the CPU could be quite considerable, to the point that your browser could stop responding.
Drawing a Significant Number of Objects on a Small Surface
Another example is a scenario where your application needs to draw a significant number of objects on a relatively small surface — such as non-interactive real-time data visualizations like graphical representations of weather patterns.
The above image is from this MSDN article, which was part of my research for this piece.
Pixel Replacement in Videos
As demonstrated in this HTML5 Doctor article, another example where Canvas would be appropriate is when replacing a video background color with a different color, another scene, or image.
What HTML5 Canvas Isn’t So Great For
On the other hand, there are a number of cases where Canvas might not be the best choice compared to SVG.
Most scenarios where scalability is a plus are going to be better served using SVGs rather than Canvas. High-fidelity, complex graphics like building and engineering diagrams, organizational charts, biological diagrams, etc., are examples of this.
When drawn using SVG, enlarging the images or printing them preserves all the details to a high level of quality. You can also generate these documents from a database, which makes the XML format of SVG highly suited to the task.
Also, these graphics are often interactive. Think about seat maps when you’re booking your plane ticket online as an example, which makes them a great use case for a retained graphics system like SVG.
That said, with the help of some great libraries like CreateJS and Zim (which extends CreateJS), developers can relatively quickly integrate mouse events, hit tests, multitouch gestures, drag and drop capabilities, controls, and more, to their Canvas-based creations.
Although there are steps you can take to make a Canvas graphic more accessible — and a good Canvas library like Zim could be helpful here to speed up the process — canvas doesn’t shine when it comes to accessibility. What you draw on the canvas surface is just a bunch of pixels, which can’t be read or interpreted by assistive technologies or search engine bots. This is another area where SVG is preferable: SVG is just XML, which makes it readable by both humans and machines.
Combining HTML5 Canvas and SVG for Advanced Scenarios
There are cases where your application can get the best of both worlds by combining HTML5 Canvas and SVG. For instance, a Canvas-based game could implement sprites from SVG images generated by a vector editing program, to take advantage of the scalability and reduced download size compared to a PNG image. Or a paint program could have its user interface designed using SVG, with an embedded
<canvas>element, which could be used for drawing.
Finally, a powerful library like Paper.js makes it possible to script vector graphics on top of HTML5 Canvas, thereby offering devs a convenient way of working with both technologies.
In this article, I’ve explored some key features of both HTML5 Canvas and SVG to help you decide which technology might be most suited suited to particular tasks.
What’s the answer?
Chris Coyier agrees with Benjamin De Cock, as the latter tweets:
One extremely basic way to answer it is "use canvas when you cannot use svg" (where "cannot" might mean animating thousands of objects, manipulating each pixel individually, etc.). To put it another way, SVG should be your default choice, canvas your backup plan.
— Benjamin De Cock (@bdc) October 2, 2019
Dr Abstract offers a long list of things that are best built using Canvas, including interactive logos and advertising, interactive infographics, e-learning apps, and much more.
In my view, there aren’t any hard and fast rules for when it’s best to use Canvas instead of SVG. The distinction between immediate and retained mode points to HTML5 Canvas as being the undisputed winner when it comes to building things like graphic-intensive games, and to SVG as being preferable for things like flat images, icons and UI elements. However, in between there’s room for HTML5 Canvas to expand its reach, especially considering what the various powerful Canvas libraries could bring to the table. Not only do they make it easier to work with both technologies in the same graphic work, but they also make it so that some hard-to-implement features in a native Canvas-based project — like interactive controls and events, responsiveness, accessibility features, and so on — could now be at most developers’ fingertips, which leaves the door open to the possibility of ever more interesting uses of HTML5 Canvas.
Maria Antonietta Perna is a teacher and technical writer. She enjoys tinkering with cool CSS standards and is curious about teaching approaches to front-end code. When not coding or writing for the web, she enjoys reading philosophy books, taking long walks, and appreciating good food.