Kaiido / SVG2Bitmap

A small function using the ability of HTMLCanvas element to rasterize svg images
MIT License
18 stars 8 forks source link

SVG2Bitmap

JavaScript SVG to Canvas utility

This project is now dead.

We are sorry, but we don't have time to maintain it, and it started on the wrong path anyway.
It should have kept itself to only parsing and fetching external assets, instead of trying to do everything from A to Z.

You can still use it, fork it, tweak it freely, but we won't work on it anymore.

Maybe some day it's little sister SVGUnify will finally come to life.


Old readme

The script fixes some issues while drawing SVG on a HTMLcanvas with the built-in context.drawImage() method.

How does it work?

Most of the svg to canvas libraries does lack of support for external resources (xlink attributes, <images>, <funciri>, external CSS rules etc.), some svg filters or some other edge cases. The built-in drawImage() method of the CanvasRenderingContext2D does an almost perfect rendering of the svg images passed into it.
The major issue is that external resources won't load into the <img> element needed by the drawImage() method.
This script will try to append these resources into the element so they can also be rendered.

Browser compatibility

The script should work fine on the following browsers :

[1]: IE will taint the canvas so no way to get the dataURL version nor to call getImageData() onto the returned canvas.
[2]: Safari 9 does taint the canvas when a <foreignObject> is being painted on it.

Usage

You can call the script like so :

SVG2Bitmap(sourceElement, [receiver] [, {optionalParameters}]);

List of currently available optional parameters :

Simple example

SVG2Bitmap(document.querySelector('svg'), function(canvas, dataURL){
    document.body.appendChild(canvas);
});

Note

A custom property of the returned canvas named originalSVG will keep a link to the original svg node.

Limitations

More examples

Will never come...