I had always created Konva stages by setting the container parameter to the selector of an existing HTML DIV element. Then I needed to create an image from canvas elements as a one-off which I would then draw into the main stage. So how to do that without having a physical, in-the-DOM container DIV?
Looking a the docs and source code for the Stage, it turns out that the container can be an in-the-DOM DIV, or a DIV that we create as a new element that is NOT in the DOM.
let newDiv = document.createElement("div"),
stage = new Konva.Stage({
container: newDiv,
width: 400,
height: 500
});You can draw shapes into the stage created above, you just can't see it in the DOM.
You may have experienced the issue where nw DIV elements not yet added into the DOM do not have size. The good news is that this Stage (HTML5 canvas) will perform as required for all drawing operations.
Update - enter the OffscreenCanvas
It's 2024 now and we have the OffscreenCanvas - MDN's description of this is...
<canvas> element or the Canvas API, rendering, animation, and user interaction usually happen on the main execution thread of a web application. The computation relating to canvas animations and rendering can have a significant impact on application performance.The
OffscreenCanvas interface provides a canvas that can be rendered off screen, decoupling the DOM and the Canvas API so that the <canvas> element is no longer entirely dependent on the DOM. Rendering operations can also be run inside a worker context, allowing you to run some tasks in a separate thread and avoid heavy work on the main thread.That pretty much tells you why the OffscreenCanvas is a good advance in canvas technology.
And specific reasons for considering this approach?
In my intro I mentioned that I had to create an image from canvas elements as a one-off, which I did by drawing to an off screen canvas and converting to a standard image which was used in a Konva.Image as usual. That was useful.
Also, MDN's page on Optimising Canvas has a few points about optimising images so that you only scale them once - not on every canvas refresh. This is the kind of low-level detail that can help boost performance of your app, and its where an offscreen canvas can come to bear.
Thanks for reading.
VW May 2024
Photo by Monstera Production