Search code examples
konvajskonva

How to get clicked element's position and id to change color and draw lines on it


I'm developing a basic window frame configurator. I splitted glasses in function below. I want to change color when i clicked and get the position of clicked glass to draw openin direction lines. I tried to understand and implement Lavrton's method(https://codesandbox.io/s/0xj7zml2zl?file=/src/index.js) but i couldn't succeed.

function glassDraw(piece, frameWidth, frameHeight) {

var glassGroup = new Konva.Group();

for (i = 0; i <piece; i++) {
    var glass = new Konva.Rect({
        name: 'Rect',
        x: padding + (frameWidth / piece) * i,
        y: padding,
        width: frameWidth / piece,
        height: frameHeight - padding * 2,
        fill: 'lightblue',
        id: 'glass'+i,
        
    });
  

    glassGroup.add(glass);
    
} 
glassGroup.find("Rect").on('click', function (e) {
    // get id of the cube i drag
    var clickedId = e.target.attrs.id;
    
    $('#theId').html(clickedId);
 
})
return glassGroup;

}

When i use getelementbyid method with id of konva element("glass"+i), it returns null. I think i need to get as a konva element.


Solution

  • You have to create a click listener for all of your rectangles.

    for (let rect of glassGroup.children) {
        rect.on('click', () => {
    
            console.log(rect.x(), rect.y()); // current position of the object
            console.log(rect.id()); // log id of the object
            rect.fill('green'); // set color to green
            layer.batchDraw(); // update layer (batchDraw just for better performance .draw() would work to)
    })
    

    }

    Make sure you always update the stage by either call stage.draw() or layer.draw() (or batchDraw() for better performance) after changing something, otherwise your stage will not show anything of what you do.

    If something with this code don't work feel free to ask.

    Have a nice day.