Canvas and SVG allow web developers to draw images onto the screen, but they have very different APIs and approaches to doing so.

So, you need to add some charts to your app or site? By now you’ve figured out that there are many different ways to accomplish this, most of which utilize one of two primary technologies: SVG and the Canvas API.

In order to decide which will best fit your needs, we need to look at SVG’s and Canvas’s relative strengths and weaknesses and how those play into the different chart-drawing solutions available.

Canvas and SVG are both technologies that allow web developers to draw images onto the screen, but they have very different APIs and approaches to doing so.

What is SVG?

SVG stands for “scalable vector graphics” and represents a body of standards for declaratively defining the properties of an image (things like the shapes themselves, fill color, stroke color, and the like).

<svg width="100" height="100" xmlns="http://www.w3.org/2000/svg">
  <circle cx="50" cy="50" r="45" fill="#FFA69E" />
</svg>

Simple SVG Circle Result

SVG images are created either inline with HTML code by adding an <svg> tag, or can be defined in separate files (with the .svg extension) and referenced in the HTML.

What is Canvas?

Canvas is a lower-level browser standard API that allows developers to imperatively “draw” directly onto the image by issuing a series of commands:

const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
ctx.fillStyle = '#FFA69E';
ctx.arc(50, 50, 45, 0, 2 * Math.PI);
ctx.fill();

Simple Canvas Circle Result

Canvas images are created by adding a <canvas> element to the HTML and then manipulating that element via the JavaScript DOM API as shown above.

#svg #canvas #web-development #javascript

Using SVG vs. Canvas: A Short Guide
2.65 GEEK