UNPKG

6.9 kBMarkdownView Raw
1# canvg
2
3[![NPM version][npm]][npm-url]
4[![Dependencies status][deps]][deps-url]
5[![Build status][build]][build-url]
6[![Coverage status][coverage]][coverage-url]
7[![Dependabot badge][dependabot]][dependabot-url]
8[![Documentation badge][documentation]][documentation-url]
9
10[npm]: https://img.shields.io/npm/v/canvg.svg
11[npm-url]: https://npmjs.com/package/canvg
12
13[deps]: https://david-dm.org/canvg/canvg.svg
14[deps-url]: https://david-dm.org/canvg/canvg
15
16[build]: http://img.shields.io/travis/com/canvg/canvg/master.svg
17[build-url]: https://travis-ci.com/canvg/canvg
18
19[coverage]: https://img.shields.io/coveralls/canvg/canvg.svg
20[coverage-url]: https://coveralls.io/r/canvg/canvg
21
22[dependabot]: https://api.dependabot.com/badges/status?host=github&repo=canvg/canvg
23[dependabot-url]: https://dependabot.com/
24
25[documentation]: https://img.shields.io/badge/API-Documentation-2b7489.svg
26[documentation-url]: https://canvg.github.io/canvg
27
28JavaScript SVG parser and renderer on Canvas. It takes the URL to the SVG file or the text of the SVG file, parses it in JavaScript and renders the result on Canvas.
29
30[Demo](https://canvg.github.io/canvg/demo/index.html)
31
32[Playground](https://jsfiddle.net/0q1vrjxk/)
33
34## Install
35
36```sh
37npm i canvg
38# or
39yarn add canvg
40```
41
42## Usage
43
44Basic module exports:
45
46```js
47export default Canvg;
48export {
49 presets
50};
51```
52
53[Description of all exports you can find in Documentation.](https://canvg.github.io/canvg/index.html)
54
55### Example
56
57```js
58import Canvg from 'canvg';
59
60let v = null;
61
62window.onload = async () => {
63
64 const canvas = document.querySelector('canvas');
65 const ctx = canvas.getContext('2d');
66
67 v = await Canvg.from(ctx, './svgs/1.svg');
68
69 // Start SVG rendering with animations and mouse handling.
70 v.start();
71};
72
73window.onbeforeunload = () => {
74 v.stop();
75};
76```
77
78<details>
79 <summary>
80 <b>OffscreenCanvas</b>
81 </summary>
82
83```js
84import Canvg, {
85 presets
86} from 'canvg';
87
88self.onmessage = async (event) => {
89
90 const {
91 width,
92 height,
93 svg
94 } = event.data;
95 const canvas = new OffscreenCanvas(width, height);
96 const ctx = canvas.getContext('2d');
97 const v = await Canvg.from(ctx, svg, presets.offscreen());
98
99 // Render only first frame, ignoring animations and mouse.
100 await v.render();
101
102 const blob = await canvas.convertToBlob();
103 const pngUrl = URL.createObjectURL(blob);
104
105 self.postMessage({
106 pngUrl
107 });
108};
109```
110
111</details>
112
113<details>
114 <summary>
115 <b>NodeJS</b>
116 </summary>
117
118```js
119import {
120 promises as fs
121} from 'fs';
122import {
123 DOMParser
124} from 'xmldom';
125import * as canvas from 'canvas';
126import fetch from 'node-fetch';
127import Canvg, {
128 presets
129} from 'canvg';
130
131const preset = presets.node({
132 DOMParser,
133 canvas,
134 fetch
135});
136
137(async (output, input) => {
138
139 const svg = await fs.readFile(input, 'utf8');
140 const canvas = preset.createCanvas(800, 600);
141 const ctx = canvas.getContext('2d');
142 const v = Canvg.fromString(ctx, svg, preset);
143
144 // Render only first frame, ignoring animations.
145 await v.render();
146
147 const png = canvas.toBuffer();
148
149 await fs.writeFile(output, png);
150
151})(
152 process.argv.pop(),
153 process.argv.pop()
154);
155```
156
157</details>
158
159<details>
160 <summary>
161 <b>Resize</b>
162 </summary>
163
164```js
165import Canvg, {
166 presets
167} from 'canvg';
168
169self.onmessage = async (event) => {
170
171 const {
172 width,
173 height,
174 svg
175 } = event.data;
176 const canvas = new OffscreenCanvas(width, height);
177 const ctx = canvas.getContext('2d');
178 const v = await Canvg.from(ctx, svg, presets.offscreen());
179
180 /**
181 * Resize SVG to fit in given size.
182 * @param width
183 * @param height
184 * @param preserveAspectRatio
185 */
186 v.resize(width, height, 'xMidYMid meet');
187
188 // Render only first frame, ignoring animations and mouse.
189 await v.render();
190
191 const blob = await canvas.convertToBlob();
192 const pngUrl = URL.createObjectURL(blob);
193
194 self.postMessage({
195 pngUrl
196 });
197};
198```
199
200</details>
201
202<details>
203 <summary>
204 <b>Browser</b>
205 </summary>
206
207```html
208<script type="text/javascript" src="https://unpkg.com/canvg@3.0.4/lib/umd.js"></script>
209<script type="text/javascript">
210window.onload = () => {
211
212 const canvas = document.querySelector('canvas');
213 const ctx = canvas.getContext('2d');
214
215 v = canvg.Canvg.fromString(ctx, '<svg width="600" height="600"><text x="50" y="50">Hello World!</text></svg>');
216
217 // Start SVG rendering with animations and mouse handling.
218 v.start();
219
220};
221</script>
222<canvas />
223```
224
225</details>
226
227### Options
228
229The third parameter of `new Canvg(...)`, `Canvg.from(...)` and `Canvg.fromString(...)` is options:
230
231```ts
232interface IOptions {
233 /**
234 * WHATWG-compatible `fetch` function.
235 */
236 fetch?: typeof fetch;
237 /**
238 * XML/HTML parser from string into DOM Document.
239 */
240 DOMParser?: typeof DOMParser;
241 /**
242 * Window object.
243 */
244 window?: Window;
245 /**
246 * Whether enable the redraw.
247 */
248 enableRedraw?: boolean;
249 /**
250 * Ignore mouse events.
251 */
252 ignoreMouse?: boolean;
253 /**
254 * Ignore animations.
255 */
256 ignoreAnimation?: boolean;
257 /**
258 * Does not try to resize canvas.
259 */
260 ignoreDimensions?: boolean;
261 /**
262 * Does not clear canvas.
263 */
264 ignoreClear?: boolean;
265 /**
266 * Scales horizontally to width.
267 */
268 scaleWidth?: number;
269 /**
270 * Scales vertically to height.
271 */
272 scaleHeight?: number;
273 /**
274 * Draws at a x offset.
275 */
276 offsetX?: number;
277 /**
278 * Draws at a y offset.
279 */
280 offsetY?: number;
281 /**
282 * Will call the function on every frame, if it returns true, will redraw.
283 */
284 forceRedraw?(): boolean;
285 /**
286 * Default `rem` size.
287 */
288 rootEmSize?: number;
289 /**
290 * Default `em` size.
291 */
292 emSize?: number;
293 /**
294 * Function to create new canvas.
295 */
296 createCanvas?: (width: number, height: number) => HTMLCanvasElement | OffscreenCanvas;
297 /**
298 * Function to create new image.
299 */
300 createImage?: (src: string, anonymousCrossOrigin?: boolean) => Promise<CanvasImageSource>;
301 /**
302 * Load images anonymously.
303 */
304 anonymousCrossOrigin?: boolean;
305}
306```
307
308#### Options presets
309
310There are two options presets:
311
312- `presets.offscreen()`: options for [`OffscreenCanvas`](https://developer.mozilla.org/en-US/docs/Web/API/OffscreenCanvas);
313- `presets.node({ DOMParser, canvas, fetch })`: options for NodeJS with [`node-canvas`](https://github.com/Automattic/node-canvas).
314
315## What's implemented?
316
317The end goal is everything from the [SVG spec](http://www.w3.org/TR/SVG/). The majority of the rendering and animation is working. If you would like to see a feature implemented, don't hesitate to add it to the issues list, or better is to create pull request 😎