1

I need to position text inputs at various places on a KonvaJS layer. I found the following code at https://konvajs.github.io/docs/sandbox/Editable_Text.html and I'm trying to understand the textPosition, stageBox, and areaPosition vars in this code. I want my stage centered in the browser window, but when I do that, the textarea (activated on dblclick) pops up way off to the left. I can't get a console readout of the x/y coordinates, so I can't visualize how the positioning works &, thus, how to change it. Can anyone explain, or point me in the right direction?

var text_overlay = new Konva.Layer();
stage.add(text_overlay);

var textNode = new Konva.Text({
    text: 'Some text here',
    x: 20,
    y: 50,
    fontSize: 20
});

text_overlay.add(textNode);
text_overlay.draw();

textNode.on('dblclick', () => {
    // create textarea over canvas with absolute position

    // first we need to find its position
    var textPosition = textNode.getAbsolutePosition();    
    var stageBox = stage.getContainer().getBoundingClientRect();

    var areaPosition = {
        x: textPosition.x + stageBox.left,
        y: textPosition.y + stageBox.top
    };

    // create textarea and style it
    var textarea = document.createElement('textarea');
    document.body.appendChild(textarea);

    textarea.value = textNode.text();
    textarea.style.position = 'absolute';
    textarea.style.top = areaPosition.y + 'px';
    textarea.style.left = areaPosition.x + 'px';
    textarea.style.width = textNode.width();

    textarea.focus();

    textarea.addEventListener('keydown', function (e) {
        // hide on enter
        if (e.keyCode === 13) {
            textNode.text(textarea.value);
            text_overlay.draw();
            document.body.removeChild(textarea);
        }
    });
})

// add the layer to the stage
stage.add(text_overlay);

UPDATE: I solved part of the problem--the textarea showing up way out of position. You need to use 2 divs in the HTML file instead of one, like so:

<div id="containerWrapper" align="center"><div id="container"></div></div>

Thanks to Frens' answer on Draw border edges of the Konvajs container Stage in html for that one!

las794
  • 45
  • 1
  • 9

0 Answers0