Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
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
- Host: GitHub
- URL: https://github.com/Experience-Monks/svg-to-image
- Owner: Experience-Monks
- License: mit
- Created: 2015-09-23T22:28:25.000Z (about 9 years ago)
- Default Branch: master
- Last Pushed: 2016-04-12T03:29:16.000Z (over 8 years ago)
- Last Synced: 2024-10-31T16:51:02.530Z (13 days ago)
- Language: JavaScript
- Homepage:
- Size: 9.77 KB
- Stars: 102
- Watchers: 10
- Forks: 14
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE.md
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.