[Fixed] Export konva to image in server side without render


I have a template for image and when user change image inside template, server will automatically render a new image for user. That’s all I want to make.

I have a json from template which I created before. And now i want to export it on server side (expressjs, restful api) with Konva init by json.

When I try this code

import {Stage} from 'konva/lib/core';
app.get('/', (_req: Request, res: Response, _next: NextFunction) =>
        message: loadKonvaJson(),

const loadKonvaJson = () => {
    let stage = new Stage({
        container: 'container'

    return stage.toDataURL({pixelRatio: 1});

I have an error

ReferenceError: document is not defined
    at Object.createCanvasElement (C:\Users\victorlee\Desktop\OmgGame\render-image-server\node_modules\konva\lib\Util.js:355:22)
    at getDevicePixelRatio (C:\Users\victorlee\Desktop\OmgGame\render-image-server\node_modules\konva\lib\Canvas.js:26:30)
    at SceneCanvas.Canvas (C:\Users\victorlee\Desktop\OmgGame\render-image-server\node_modules\konva\lib\Canvas.js:46:74)
    at new SceneCanvas (C:\Users\victorlee\Desktop\OmgGame\render-image-server\node_modules\konva\lib\Canvas.js:112:28)
    at Stage._buildDOM (C:\Users\victorlee\Desktop\OmgGame\render-image-server\node_modules\konva\lib\Stage.js:717:29)
    at new Stage (C:\Users\victorlee\Desktop\OmgGame\render-image-server\node_modules\konva\lib\Stage.js:62:15)
    at loadKonvaJson (C:\Users\victorlee\Desktop\OmgGame\render-image-server\index.ts:20:17)
    at exports.app.get (C:\Users\victorlee\Desktop\OmgGame\render-image-server\index.ts:17:14)
    at Layer.handle [as handle_request] (C:\Users\victorlee\Desktop\OmgGame\render-image-server\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\Users\victorlee\Desktop\OmgGame\render-image-server\node_modules\express\lib\router\route.js:137:13)


Do not use container property when you are trying to use Konva from nodejs. Just:

let stage = new Stage({});

Konva is trying to find the container in the DOM, but there is not DOM in nodejs env.

Update: also for the nodejs environment you have to use konva-node package:

cont Konva = require('konva-node');

const stage = new Konva.Stage({
  width: 100,
  height: 100

Leave a Reply

(*) Required, Your email will not be published