如何获得 SVG.JS 3.0.+ 使用 svgdom 和 node.js

How to get SVG.JS 3.0.+ working with svgdom and node.js

SVG.js 3.0.5 已经发布,我想更新我的 nodejs 应用程序,它使用从 2.7 到 3.0.5 的库生成 svgs。

运行 这个库 node.js 你需要使用 svgdom (https://github.com/svgdotjs/svgdom)

这里的问题是构造函数改变了,我不知道如何将它与 node.js 一起使用。

//previous method to initialize svgjs 2.7
const svgWindow   = require('svgdom');
const SVGJS = require("svg.js")(svgWindow);

//with version 3.0.5 the package name changed
const svgWindow = require("svgdom");
const SVGJS = require("@svgdotjs/svg.js");

SVGJS(svgWindow); //is not a function error

我查看了源代码,看起来应该可以工作

const window = require("svgdom");
const SVG = require("@svgdotjs/svg.js");

SVG.registerWindow(window, window.document);

我更新了自述文件以更好地反映新用途:

npm install @svgdotjs/svg.js svgdom

// returns a window with a document and an svg root node
const window = require('../svgdom')
const document = window.document
const {SVG, registerWindow} = require('@svgdotjs/svg.js')

// register window and document
registerWindow(window , window.document)

// create canvas
const canvas = SVG(document.documentElement)

// use svg.js as normal
canvas.rect(100,100).fill('yellow').move(50,50)

// get your svg as string
console.log(canvas.svg())
// or
console.log(canvas.node.outerHTML)

请注意,svg.js v3 不再导出这个大对象。相反,您必须要求您需要的功能。自述文件中的更多信息:https://github.com/svgdotjs/svgdom