gliffy / canvas2svg

Translates HTML5 Canvas draw commands to SVG
MIT License
683 stars 155 forks source link

Using with Node.JS #78

Closed d1soft closed 3 years ago

d1soft commented 3 years ago

I faced problem with missed XMLSerializer.


(node:19466) UnhandledPromiseRejectionWarning: ReferenceError: XMLSerializer is not defined
    at ctx.getSerializedSvg (/home/work/schema-docs/node_modules/canvas2svg/canvas2svg.js:396:26)
    at ERDGenerator.asSvg (/home/work/schema-docs/src/ERDGenerator.ts:184:29)
    at /home/liteman/work/schema-docs/src/DocsGenerator.ts:75:42
    at DocsGenerator.generate (/home/work/schema-docs/src/DocsGenerator.ts:42:21)
(node:19466) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:19466) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code
```.
d1soft commented 3 years ago

canvas2svg use global defined XMLSerializer. To avoid this problem, you can define globaly XMLSerializer. My snippet with ts, jsdom, c2s


import { JSDOM } from 'jsdom';
import { XMLSerializer } from 'xmldom';
const canvas2svg = require('canvas2svg');
///
public asSvg(): string {
    const document = new JSDOM();
    // unnecessery line, but just in case
    document.window.XMLSerializer = XMLSerializer;
    // define globaly window, just in case too :)
    global.window = document.window as any
    // define globaly XMLSerializer
    global.XMLSerializer = XMLSerializer;

     // now you can use c2s without a headache
     const context = new canvas2svg({
         document: document.window.document
    });

    this.buildContext(context);
    return context.getSerializedSvg();
}