Coder Perfect

Using an HTML5 canvas to draw an SVG file


Is there a method to draw an SVG file onto an HTML5 canvas by default? Google Chrome allows you to load the SVG as an image (and then render it), but the developer console warns that the resource was interpreted as an image but was sent with the MIME type image/svg+xml.

I’m aware that converting SVG to canvas instructions (as in this question) is an option, but I’m hoping that’s not necessary. I’m not concerned with older browsers (if FireFox 4 and Internet Explorer 9 can support anything, that’s fine with me).

Asked by Randy Voet

Solution #1

All major browsers now support the Path2D() constructor, which “allows path objects to be specified on 2D canvas surfaces.”

In certain but not all browsers, you may now use ctx.drawImage to draw HTMLImageElements with a.svg source (75 percent coverage: Chrome, IE11, and Safari work, Firefox works with some bugs, but nightly has fixed them).

var img = new Image();
img.onload = function() {
    ctx.drawImage(img, 0, 0);
img.src = "";

Here is a real-life example. In the canvas, there should be a green square. The same svg> element has been placed into the DOM for reference in the second green square on the page.

You may also draw SVG (string) routes with the new Path2D objects. To put it another way, you can write:

var path = new Path2D('M 100,100 h 50 v 50 h 50');

Here’s a real-life illustration of that.

There isn’t anything native in canvas that allows you to use SVG paths. You can either convert it yourself or have it done for you by a library.

I recommend checking into canvg: (See the homepage and demos)

Answered by Simon Sarris

Solution #2

Further to @Matyas answer: if the svg’s image is also in base64, it will be drawn to the output.

Answered by Henrique Campos

Solution #3

Simple svgs can be readily drawn onto a canvas by:

The method’s only drawback is that it can’t draw graphics embedded in svg files. (example)

(The attached image is only viewable in the svg file.)

Answered by Matyas

Solution #4

“Drawing DOM objects into a canvas” is an easy technique for Mozilla to draw SVG on canvas.

Answered by Nati Krisi

Solution #5

As Simon says above, using drawImage shouldn’t work. However, if you use the canvg library and:

var c = document.getElementById('canvas');
var ctx = c.getContext('2d');
ctx.drawSvg(SVG_XML_OR_PATH_TO_SVG, dx, dy, dw, dh);

This is taken from the link provided by Simon above, which includes a number of other options as well as the recommendation to link to or download canvg.js and rgbcolor.js. These allow you to alter and load an SVG from within JavaScript methods, either via URL or inline SVG code within svg tags.

Answered by Max West

Post is based on