Search code examples
canvaskonvajsreact-konvakonvakonvajs-reactjs

react-konva Free hand area selection using mouse click (straight lines)


I want to implement a free hand area selection on canvas using react-konva. Anyone have solution or suggestion ?
Please refer screenshot for better understanding.
Thank You !!!

And I tried this, https://codesandbox.io/s/dry-flower-b5eof-b5eof

Area selection using free hand selection on canvas


Solution

  • Conceptually you are collecting the points for a polygon. You will have to decide how your UI should inform the user how to 'close' the shape. Once the user has closed the shape, remove the lines and draw a Konva.Polygon using the x + y values of the polygon corners as the points array. You can fill the polygon with color via its normal fill() attribute.

    Regarding how to inform the user to 'close' the shape, there's no right or wrong here - its whatever UI you design. You might want to go for letting the user click near to the start point to indicate the close. If you take this course, you need to do some test on the mouse click point and decide if it is 'near enough' to the start point to indicate the user wants to close the figure.

    Here is some code to help you with that. It is testing whether the mouse click is within a circle (not a circle shape, just in math terms) placed at a specific point (your start drawing point) with a specific radius (how accurate does the user need to be?).

    // Javascript program to check if a point
    // lies inside a circle or not 
    // from https://www.geeksforgeeks.org/find-if-a-point-lies-inside-or-on-circle/
    function isInside(circle_x, circle_y, rad, x, y)
    {
         
        // Compare radius of circle with
        // distance of its center from
        // given point
         
        if ((x - circle_x) * (x - circle_x) +
            (y - circle_y) * (y - circle_y) <= rad * rad)
            return true;
        else
            return false;
    }
    

    So - now you can know when the user wants to close the shape, then you will have the array of points for the polygon. You would erase the line shape and then add the polygon.