Security News
Cloudflare Adds Security.txt Setup Wizard
Cloudflare has launched a setup wizard allowing users to easily create and manage a security.txt file for vulnerability disclosure on their websites.
The canvg npm package is a versatile library that allows users to parse and render SVG (Scalable Vector Graphics) to a Canvas element in a browser or on the server-side using Node.js. It is particularly useful for converting SVGs into Canvas for manipulation, rendering, or exporting purposes.
Rendering SVG to Canvas
This code sample demonstrates how to load an SVG file, render it onto a Canvas, and then save the Canvas output as a PNG file. This is useful for server-side generation of images from SVG files.
const canvg = require('canvg');
const Canvas = require('canvas');
const fs = require('fs');
const canvas = Canvas.createCanvas(800, 600);
const ctx = canvas.getContext('2d');
const svg = fs.readFileSync('path/to/your/svgfile.svg', 'utf-8');
canvg(ctx, svg);
const out = fs.createWriteStream('path/to/output.png');
const stream = canvas.createPNGStream();
stream.pipe(out);
Manipulating SVG before rendering
This example shows how to manipulate SVG data by changing its color before rendering it to a Canvas. This is useful for dynamically altering the appearance of SVGs based on runtime conditions.
const canvg = require('canvg');
const Canvas = require('canvas');
const fs = require('fs');
const canvas = Canvas.createCanvas(800, 600);
const ctx = canvas.getContext('2d');
let svg = fs.readFileSync('path/to/your/svgfile.svg', 'utf-8');
// Modify SVG data
svg = svg.replace('fill:#000000', 'fill:#123456');
// Render modified SVG to canvas
canvg(ctx, svg);
Fabric.js is a powerful and rich graphics library, allowing you to manipulate and render both SVG and Canvas elements. Compared to canvg, Fabric.js offers a broader set of features for interactive object model on canvas, including a full suite of interactive capabilities such as drag and drop, object manipulation, and events.
svg2canvas is another library that focuses on converting SVG documents into Canvas elements. While similar in purpose to canvg, svg2canvas might have different implementation details or performance characteristics, making it a viable alternative depending on specific project requirements.
JavaScript 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.
npm i canvg
# or
yarn add canvg
Basic module exports:
export default Canvg;
export {
presets
};
Description of all exports you can find in Documentation.
import Canvg from 'canvg';
let v = null;
window.onload = async () => {
const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
v = await Canvg.from(ctx, './svgs/1.svg');
// Start SVG rendering with animations and mouse handling.
v.start();
};
window.onbeforeunload = () => {
v.stop();
};
import Canvg, {
presets
} from 'canvg';
self.onmessage = async (event) => {
const {
width,
height,
svg
} = event.data;
const canvas = new OffscreenCanvas(width, height);
const ctx = canvas.getContext('2d');
const v = await Canvg.from(ctx, svg, presets.offscreen());
// Render only first frame, ignoring animations and mouse.
await v.render();
const blob = await canvas.convertToBlob();
self.postMessage({
pngUrl: blob
});
};
import {
promises as fs
} from 'fs';
import {
DOMParser
} from 'xmldom';
import * as canvas from 'canvas';
import fetch from 'node-fetch';
import Canvg, {
presets
} from 'canvg';
const preset = presets.node({
DOMParser,
canvas,
fetch
});
(async (output, input) => {
const svg = await fs.readFile(input, 'utf8');
const canvas = preset.createCanvas(800, 600);
const ctx = canvas.getContext('2d');
const v = Canvg.fromString(ctx, svg, preset);
// Render only first frame, ignoring animations.
await v.render();
const png = canvas.toBuffer();
await fs.writeFile(output, png);
})(
process.argv.pop(),
process.argv.pop()
);
import Canvg, {
presets
} from 'canvg';
self.onmessage = async (event) => {
const {
width,
height,
svg
} = event.data;
const canvas = new OffscreenCanvas(width, height);
const ctx = canvas.getContext('2d');
const v = await Canvg.from(ctx, svg, presets.offscreen());
/**
* Resize SVG to fit in given size.
* @param width
* @param height
* @param preserveAspectRatio
*/
v.resize(width, height, 'xMidYMid meet');
// Render only first frame, ignoring animations and mouse.
await v.render();
const blob = await canvas.convertToBlob();
self.postMessage({
pngUrl: blob
});
};
<script type="text/javascript" src="https://unpkg.com/canvg@3.0.0-beta.0/lib/umd.js"></script>
<script type="text/javascript">
window.onload = () => {
const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
v = canvg.Canvg.fromString(ctx, '<svg width="600" height="600"><text x="50" y="50">Hello World!</text></svg>');
// Start SVG rendering with animations and mouse handling.
v.start();
};
</script>
<canvas />
The third parameter of new Canvg(...)
, Canvg.from(...)
and Canvg.fromString(...)
is options:
interface IOptions {
/**
* WHATWG-compatible `fetch` function.
*/
fetch?: typeof fetch;
/**
* XML/HTML parser from string into DOM Document.
*/
DOMParser?: typeof DOMParser;
/**
* Window object.
*/
window?: Window;
/**
* Whether enable the redraw.
*/
enableRedraw?: boolean;
/**
* Ignore mouse events.
*/
ignoreMouse?: boolean;
/**
* Ignore animations.
*/
ignoreAnimation?: boolean;
/**
* Does not try to resize canvas.
*/
ignoreDimensions?: boolean;
/**
* Does not clear canvas.
*/
ignoreClear?: boolean;
/**
* Scales horizontally to width.
*/
scaleWidth?: number;
/**
* Scales vertically to height.
*/
scaleHeight?: number;
/**
* Draws at a x offset.
*/
offsetX?: number;
/**
* Draws at a y offset.
*/
offsetY?: number;
/**
* Will call the function on every frame, if it returns true, will redraw.
*/
forceRedraw?(): boolean;
/**
* Default `rem` size.
*/
rootEmSize?: number;
/**
* Default `em` size.
*/
emSize?: number;
/**
* Function to create new canvas.
*/
createCanvas?: (width: number, height: number) => HTMLCanvasElement | OffscreenCanvas;
/**
* Function to create new image.
*/
createImage?: (src: string) => Promise<CanvasImageSource>;
}
There are two options presets:
presets.offscreen()
: options for OffscreenCanvas
;presets.node({ DOMParser, canvas, fetch })
: options for NodeJS with node-canvas
.The end goal is everything from the SVG spec. 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 😎
FAQs
JavaScript SVG parser and renderer on Canvas.
The npm package canvg receives a total of 1,168,634 weekly downloads. As such, canvg popularity was classified as popular.
We found that canvg demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Cloudflare has launched a setup wizard allowing users to easily create and manage a security.txt file for vulnerability disclosure on their websites.
Security News
The Socket Research team breaks down a malicious npm package targeting the legitimate DOMPurify library. It uses obfuscated code to hide that it is exfiltrating browser and crypto wallet data.
Security News
ENISA’s 2024 report highlights the EU’s top cybersecurity threats, including rising DDoS attacks, ransomware, supply chain vulnerabilities, and weaponized AI.