SVG or canvas?





SVG and canvas are technologies that you can use to draw something on web pages. Therefore, they should be compared and figured out when to use SVG, and when to use canvas. Even a very superficial understanding of the essence of these technologies allows you to make a very informed choice. As a matter of fact, here are two typical situations, in one of which you should prefer SVG, and in the other - canvas:





The author of the article, the translation of which we are publishing today, says that he knows that he has not yet revealed the reasons for this choice. But he hopes these reasons will become completely apparent after he shares some details about SVG and canvas.



SVG - vector graphics described declaratively



If you know that you need to place a vector image on a web page, that means SVG is right for you. Vector images usually look better than similar raster images stored, for example, in JPG files. In addition, vector image files are usually smaller than raster image files.



The result is that SVG is very often used to draw logos . Code describing such images can be embedded directly into HTML. It looks like a set of declarative instructions:



<svg viewBox="0 0 100 100">   <circle cx="50" cy="50" r="50" /> </svg>
      
      





If you need images to be flexible and responsive, then SVG is your choice.



Canvas - JavaScript API for drawing



To create canvas images in the HTML code of the page, place the <canvas>



, after which, using JavaScript, they "draw" on this element. In other words, the programmer gives the browser instructions regarding how he needs to draw something (this approach is closer to the imperative than to the declarative). Here's what it looks like:



 <canvas id="myCanvas" width="578" height="200"></canvas> <script>  var canvas = document.getElementById('myCanvas');  var context = canvas.getContext('2d');  var centerX = canvas.width / 2;  var centerY = canvas.height / 2;  var radius = 70;  context.beginPath();  context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);  context.fillStyle = 'green';  context.fill(); </script>
      
      





SVG images are stored in the DOM



If you are familiar with DOM events, such as click



and mouseDown



, then be aware that these events can also be used when working with SVG. In this regard, the SVG <circle>



element is not very different from the HTML <div>



element.



 <svg viewBox="0 0 100 100">   <circle cx="50" cy="50" r="50" />   <script>    document.querySelector('circle').addEventListener('click', e => {      e.target.style.fill = "red";    });  </script> </svg>
      
      





SVG is better for making page content accessible



The canvas element can be assigned its text alternative:



 <canvas aria-label="Hello ARIA World" role="img"></canvas>
      
      





The same can be done for the SVG element. But, since SVG images and their internal mechanisms are stored directly in the DOM, SVG is usually considered as a technology used in cases when they create projects that are accessible for people with disabilities.



In other words, you can create an SVG image with elements of which assistive technologies can work, helping their users navigate web pages.



The text data that is part of the images is also the case when it is preferable to use SVG. SVG even has a special element - <text>



. It allows you to display clear characters of texts, it is perceived by assistive technology . If you use the canvas element for visualizing texts, such texts are often displayed poorly and look blurry.



Canvas is better for working with individual pixel images.



Below we give several tables compiled on the basis of comparing SVG and canvas by various experts. In one such comparison, performed by Sarah Drasner, it is said that using canvas you can make pixels dance. This, of course, is a joke, but, in essence, it is.



Canvas is great for creating interactive images that contain a lot of complex details, gradient color transitions, and more. For this reason, canvas is used in the development of a much larger number of browser games than SVG. Although, of course, you can always find deviations from general trends. Here , for example, is a game whose graphics are created using SVG tools.









SVG game



Please note that its graphic component is very simple and looks quite “vector”.



CSS images can be influenced using CSS



We have already said that SVG elements are stored in the DOM, and that access to these elements can be obtained from JavaScript code. In the case of CSS, this story repeats itself:



 <svg viewBox="0 0 100 100">   <circle cx="50" cy="50" r="50" />   <style>    circle { fill: blue; }  </style> </svg>
      
      





Please note that in the examples the <script>



and <style>



blocks are placed inside the <svg>



block. This is perfectly normal. But taking into account the fact that the SVG element is in plain HTML code, it turns out that the internal <script>



and <style>



blocks can be completely removed from it. In addition, if necessary, you can work on the SVG element using external styles and scripts.



Here is a lot of material about the properties of SVG elements and CSS. The most important thing here is that everything that can be done with page elements using CSS applies to SVG. For example, this is using the :hover



pseudo- :hover



and animating elements.



Here's an example of animating a <circle>



element with CSS.



 <svg viewBox="0 0 100 100">   <circle cx="50" cy="50" r="50" />   <style>    circle { fill: blue; animation: pulse 2s alternate infinite; }    @keyframes pulse {      100% {        r: 30;      }    }  </style>   <script>    document.querySelector('circle').addEventListener('click', e => {      e.target.style.fill = "red";    });  </script> </svg>
      
      











CSS element animations using CSS



Combination of SVG and canvas



From a technical point of view, canvas and SVG technologies cannot be called mutually exclusive. For example, SVG images can be displayed in <canvas>



elements. At the same time, as can be seen in this example, SVG images displayed in the <canvas>



element may well remain very clear and high-quality.









Output SVG image to <canvas> element



Now let's look at a few tables that summarize comparisons between SVG and canvas made by various experts.



Comparing SVG and canvas



▍Ruth John



Here is the project on the basis of which the following table is built.

Possibility

Svg

Canvas

Vector graphics

+

-
Raster graphics

- +

Access to the DOM

+

-
Availability

+

±

Text output

+

+

Conclusion of gradients and patterns

+

+

CSS animation support

+

-
CSS filter support

+

+

SVG filter support

+

+

Support for outputting image files and video files

- +

Export item content

- +

Single pixel management

- +

JavaScript access

- +

Animation Performance

±

+

Support for calculations performed outside the main thread

- +



▍ Sarah Drasner



The following table is based on this tweet.

DOM / Virtual DOM

Canvas

Benefits Great for UI / UX animation. Dance, pixels!
Great for outputting resolution independent resolution SVG images. Great for 3D graphics output and other similar use cases.
Easy to debug. Conveniently manage many moving objects.
disadvantages Images are created from many separate objects. It’s more difficult to make content accessible.
In light of the previous minus, it turns out that when animating SVG images, you need to be careful. In the standard form, canvas images are resolution dependent.
It is difficult to organize user interaction with individual image elements.


▍Shirley Wu



The following table is based on this tweet.

Svg

Canvas

Benefits

Easier to learn.

Very high performance.

Easier to organize a response to user exposure.

Easier to update.

Easier to animate.

disadvantages

You may need to use complex DOM structures.

More difficult to learn.

Low productivity when working with a large number of elements.

It’s more difficult to handle user exposure.

To animate objects, you need to write your own code.



Many people think that canvas is better for working with a large number of objects (according to Shirley - when there are more than 1000).



SVG is the standard choice. Canvas is a fallback



Here is the answer to my tweet about options for using SVG and canvas. The author of this answer says that the choice between SVG and canvas should be done like this: "Use canvas when you can not use SVG." Among the situations in which it is not possible to use SVG normally, we can mention those in which you need to animate thousands of objects, work with each specific pixel in the image, and so on.



Summary



At the beginning of this article, we presented two typical uses of SVG and canvas. Let's go back to them and expand their descriptions taking into account what we just found out.





It should be noted that between these two extreme options there is a large intermediate zone. For example, as a web developer and designer, I believe that SVG is more convenient from a practical point of view. I don’t even know if I would do some real project using canvas. Perhaps this is partly because I am not familiar enough with canvas. And I'm familiar with SVG quite well. I studied this technology, wrote a book about it. As a result, I know enough about SVG so that this technology can help me do what I need.



Dear readers! In which situations do you use SVG and in which canvas?








All Articles