Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/Experience-Monks/svg-to-image

convert SVG text to a Image that can be drawn in canvas
https://github.com/Experience-Monks/svg-to-image

Last synced: 3 days ago
JSON representation

convert SVG text to a Image that can be drawn in canvas

Awesome Lists containing this project

README

        

# svg-to-image

[![experimental](http://badges.github.io/stability-badges/dist/experimental.svg)](http://github.com/badges/stability-badges)

Converts a string of SVG into an `HTMLImageElement` using `Blob` and `URL.createObjectURL`. Falls back to `encodeURIComponent` for unsupported browsers, such as Safari 8.0.

## Install

```sh
npm install svg-to-image --save
```

## Example

A common use case for this is rendering SVG to a 2D or WebGL canvas.

```js
var svgToImage = require('svg-to-image')
var getContext = require('get-canvas-context')

// set up a new Canvas2D
var context = getContext('2d', {
width: 200, height: 200
})

var data = [
'',
'',
'',
'',
'',
'',
'',
'',
'',
''
].join('\n')

svgToImage(data, function (err, image) {
if (err) throw err

// draw image to canvas
context.drawImage(image, 0, 0)

// append to DOM
var canvas = context.canvas
document.body.appendChild(context.canvas)

// open a PNG image the user can Right Click -> Save As
window.open(context.canvas.toDataURL('image/png'))
})
```

Result:

![svgImage](http://i.imgur.com/MCXkoDu.png)

In Chrome and FireFox, you can also use this method for rendering DOM to canvas, by using `` and well-formatted HTML.

```js
var data = [
'',
'',
'

',
'I like ',
'',
'cheese
',
'
',
'',
''
].join('\n')
```

### Gotchas

- The `` element should have both `width` and `height` fields, otherwise it may lead to undefined results
- Rendering DOM needs to be wrapped in ``, be well-formatted, and the root element should use the correct XML namespace
- Only latest Chrome and FireFox have been tested with ``

## Usage

[![NPM](https://nodei.co/npm/svg-to-image.png)](https://www.npmjs.com/package/svg-to-image)

#### `svgToImage(svg, [opt], [cb])`

Converts the given `svg` string data into an `HTMLImageElement`, which can then be used to render to canvas.

You can optionally specify an `opt.crossOrigin` string, or omit the `opt` object.

The callback is called with `(err, image)` parameters, where `err` will be non-null in the case of a failure, and `image` is the rendered image.

## License

MIT, see [LICENSE.md](http://github.com/Jam3/svg-to-image/blob/master/LICENSE.md) for details.