To draw a vector SVG image, the operation is not different from a raster image :
You first need to load your SVG image into an HTMLImage element, then use the drawImage()
method.
var image = new Image();
image.onload = function(){
ctx.drawImage(this, 0,0);
}
image.src = "someFile.SVG";
SVG images have some advantages over raster ones, since you won't loose quality, whatever the scale you'll draw it on your canvas. But beware, it may also be a bit slower than drawing a raster image.
However, SVG images come with more restrictions than raster images.
For security purpose, no external content can be loaded from an SVG image referenced in an HTMLImageElement(<img>
)
No external stylesheet, no external image referenced in SVGImage (<image/>
) elements, no external filter or element linked by the xlink:href
attribute (<use xlink:href="anImage.SVG#anElement"/>
) or the funcIRI (url()
) attribute method etc.
Also, stylesheets appended in the main document won't have any effect on the SVG document once referenced in an HTMLImage element.
Finally, no script will be executed inside the SVG Image.
Workaround : You'll need to append all external elements inside the SVG itself before referrencing to the HTMLImage element. (for images or fonts, you need to append a dataURI version of your external resources).
The root element (<svg>
) must have its width and height attributes set to an absolute value.
If you were to use relative length (e.g %
), then the browser won't be able to know to what it is relative.
Some browsers (Blink) will try to make a guess, but most will simply ignore your image and won't draw anything, without a warning.
Some browsers will taint the canvas when an SVG image has been drawn to it.
Specifically, Internet-Explorer < Edge in any case, and Safari 9 when a <foreignObject>
is present in the SVG image.