konvajs/konva

NextJS server-side Stage initialization error

gabaj opened this issue · 1 comments

Hello,

I'm trying to generate some PDF files with Konva on a server side with NextJS and its API route, but I get:

TS2345: Argument of type  { width: number; height: number; }  is not assignable to parameter of type  StageConfig 
Property  container  is missing in type  { width: number; height: number; }  but required in type  StageConfig 
Stage.d.ts(7, 5):  container  is declared here.

Also when I run the code I get exception in Konva's drawStage function:

TypeError: canvas.getContext is not a function

This seems to be in conflict with readme: https://github.com/konvajs/konva?tab=readme-ov-file#4-nodejs-env

Here's minimum code example that throws these errors:

import { NextApiRequest, NextApiResponse } from "next";
import Konva from "konva";
import { CanvasRenderingContext2D, createCanvas } from "canvas";

export default async (request: NextApiRequest, response: NextApiResponse) => {
 // throws TS error
  const stage = new Konva.Stage({
    width: 500,
    height: 300,
  });

  const pageCanvas: any = createCanvas(500, 300);
  const context = pageCanvas.getContext("2d");
  stage.drawScene(context); // throws getContext() error
};

And here are package versions:

"react-konva": "^18.1.0-0",
"konva": "^9.2.3",
"canvas": "^2.11.2",
"next": "14.0.3",

Resolved with:

const createStage = (
  stageWidth: number,
  stageHeight: number,
  canvas?: any,
): Konva.Stage => {
  return new Konva.Stage({
    width: stageWidth,
    height: stageHeight,
    container: canvas ? canvas : undefined,
  });
};