Konva js transformer events


  • Adding transformer to dynamically generated shapes?
  • Vue Konva — Saving and Loading Canvas and Transform Shapes
  • Guide to canvas manipulation with React Konva
  • The Konva.Transformer – a shape with a very particular set of skills
  • Using Konva.js to annotate image with bounding boxes
  • Adding transformer to dynamically generated shapes?

    Its sceneFunc prop takes a function with the canvas context object as the first parameter and the shape method as the second parameter. The shape object is a Konva-specific method used in the fillStrokeShape method. Then, we call fillStrokeSgape on the canvas with the shape function passed in as a callback to fill the shape with the given color and draw the strokes.

    We can also pass in other props like fill and stroke to set the fill and stroke color. Event handling React Konva shapes can listen to events and then respond to the events accordingly. We set the easing to the built-in Konva. The easing changes the speed that the shape moves as a function of time. Without it, everything would move at constant speed, which is neither natural nor interesting.

    Ease out means that it moves quickly at first and then slows down afterward. To add an image, we create a window.

    Image ; img. After adding the image, we can use some built-in effects from React Konva to add some effects to our images. Blur object to the array. We need the second useEffect callback to apply the filter. It references the imageRef that we set the image to. Then we call imageRef. Resizing images with Transformer In React Konva, transformer objects let users resize images by adding handles to the shape being transformed and resizing as we do with most photo editing apps. Adding the transformation feature is a bit complex.

    Next, we have to add the onTransformationEnd prop with a function that scales the shape by the factor that the user transforms the shape to and set that as the width and height. Besides the shape component, we have to add the Transformer component as a sibling to add the handles to let users transform the shape. The onDragEnd handler enables the dragging, as we did in the earlier drag and drop example. The onTransformEnd handler has the function to resize the shape to the new width and height after the user is done dragging.

    The Transformer component has handles for resizing the circle, which is on when the isSelected prop is set to true. We set that when we click the shape in the onSelect handler of App. Basic animation We can add some basic animation effects for actions like dragging shapes around by scaling the dimensions by random factors.

    Note that we have to use use the current property to get the DOM object to call the to method. Conclusion With React Konva, we can draw many kinds of shapes with much less effort than using plain JavaScript. We can also add features to let users transform shapes and drag shapes around with ease. Even better, we can add Transformers to let users change the size of the shape like they do in photo editors. Adding images with effects is also easy with the built-in Image component and filters.

    Full visibility into production React apps Debugging React applications can be difficult, especially when users experience issues that are hard to reproduce. Instead of guessing why problems happen, you can aggregate and report on what state your application was in when an issue occurred. LogRocket also monitors your app's performance, reporting with metrics like client CPU load, client memory usage, and more.

    The LogRocket Redux middleware package adds an extra layer of visibility into your user sessions. LogRocket logs all actions and state from your Redux stores. Modernize how you debug your React apps — start monitoring for free. Share this:.

    Vue Konva — Saving and Loading Canvas and Transform Shapes

    September In a previous article , we talked about the importance of designing the landscape of an integration project using diagrammatic representations. The diagrams showcased in that article were created using INTEGRTR Digital Transformer — a specialized diagram authoring software that makes it easier than ever to visualize complex enterprise integration landscapes. Through this hands-on blog, we wanted to share our learnings and experience from the project for anyone looking to build similar tools or learn how HTML5 canvas works.

    We will start from the basics by trying to build a minimal diagram authoring tool to get you started on this journey. We will be using react for managing our DOM view layer, konva. We can select, resize and rotate the shapes in the canvas. We change the stroke color and fill color of the shapes from the right panel.

    NOTE: I will be using yarn through out the article for running scripts but you can choose to use npm as well. Just replace yarn with npm equivalent commands.

    We will add all three components to the base App component. We make them draggable and also attach data-shape attribute on each of the div to be able to identify the right shape being dragged in the event handlers. Finally add the onDragStart event handler on the div elements. The data points we pass are type of the shape, offsetX and offsetY values of the event and the dimensions of the palette node.

    We can only pass string values so we need to stringify our payload object. Now, we add our Canvas component. We offset px to consider the panel on either side.

    We only add some placeholder text here for now. Our will start to resemble our end goal. Drag and Drop shapes from the Palette to the Canvas We already have setup the shapes to be draggable in the Palette. Now we need to allow them to be dropped and added to the Canvas. For that we first need some state to track what all shapes are in the canvas at a given time and their properties like shape type, location, color, etc. We will also need this state in other components in the future like our Inspector component to update the attributes.

    So, we will make this state global. Learn more about it. We use nanoid to generate unique keys for each shape and save the x, y values passed along with the type and default values for other visual attributes like width, height, fill and stroke. We can do the same for circle and by adding radius instead of width and height.

    Remember: We set the stringified object payload in our drag start event handler We also need to know the x and y position of the drop event that Konva instance can understand so that we can add the shape at the location of the drop. To do that, we need to access the konva instance of the canvas. We can do that by attaching a ref on the Stage component.

    Now, we can access the konva instance of the canvas at stageRef. To get the correct x and y coordinate of the drop location in the Canvas, we first need to manually set the pointer position in the Konva instance as if the event was raised from within the canvas itself.

    We can do this by calling setPointersPositions on the Konva instance and passing it the event value. Then, we get the derived canvas position back by calling getPointersPositions on the konva instance. Based on the type dragged, we call the createRectangle or createCircle state updater function we created above. The offset of the mouse event in relation to the dimensions of the node that was dragged in the palette needs to be considered as well.

    To make the drop seems seamless and add the node at the exact position where drop events happen, we need to do some offset calculations. As mentioned in the diagram above, for rectangles x and y values point to the top-left corner. Therefore, we can directly subtract the offsetX and offsetY values from the x and y values we get back from Konva.

    Therefore, we first have to calculate the x and y in relation to the mid-point of the node i. Finally we subtract the resultant values from the x and y values we get back from Konva. Then, we iterate over the array to render all the shapes as children of the Layer component. We pass the key as id along with all the shape related data as shape prop to the Shape component. Now, we need to create the components that will render the actual shapes in the canvas.

    Select, Move, Resize and Rotate shapes We start with adding the state update function for selecting and moving shapes. The clearSelection handler sets the selected back to null. For moveShape handler, we first check if a shape is selected and then update the x and y coordinate values of the shape. MAX ; shape. This function is responsible for handling the resize and rotate events of a rectangle shape in canvas.

    We will be using Konva. Transformer for handling these transformations in the canvas. By default, it manipulates the scale of the shape it transforms but we need to increase width and height so that other properties like stroke width are not affected. To translate the scale change to dimension change, we first cache the order of scale changes and reset the scale of the node to the 1 default. Then, we just set the new current dimension value equal to the current dimension value multiplied by the scale order.

    MIN newBox. MAX newBox. The event needs to be prevented from bubbling to the parent context as well. This is because we will attach the clearSelection handler on the Canvas click event. We attach the handleDrag handler on dragEnd event which calls the moveShape function with the id. We also need to add the draggable boolean prop on it to start listening on the drag events. Now, we need to look at how we can listen to the resize and rotate events.

    For this we first need to attach a ref on the KonvaRectangle component to be able to access the Konva node instance of the shape. We also need to render a Transformer component with a ref attached to it. We only want the Transformer to be active when the shape is selected. So, we render it conditionally and also add an useEffect call that is run when isSelected prop changes.

    If isSelected is true, then we add the shape node instance accessed using shapeRef. We also add a boundBoxFunc on the transformer that prevents the shape from being transformed into an invalid dimension i. The only major changes are in the setup of the Transformer component.

    We have rotateEnabled set to false because there is no need to rotate a circle and also resize anchors are only available on the four corners so that the height-width ratio is always intact. You can skip the custom enabledAnchors setup if you want to allow the circle to be reshaped into an ellipse.

    To handle the clearance of selection on clicking the empty section of a canvas, we attach the clearSelection handler on the click event of the Stage component.

    But, we want to allow the user to be able to update these values. User should be able to update these values for the selected shape from the right panel. Then, in the PropertiesPanel component we first render all the properties i. And on change of any of the color inputs we call the updateAttribute function with the attribute key and the update value. This is probably the simplest of all. Instead of setting the initial state directly, we pass a function to the createStore function that checks if we have some shapes state saved in the LocalStorage and generate the initial state lazily based on that.

    We also write the saveDiagram function that just persists the shapes from the state in LocalStorage and the reset function that purges the current state as well as the LocalStorage. Finally, we add two buttons that trigger the Save and Reset actions. We have our diagram authoring tool ready for usage. It might be minimal in terms of features, but it is definitely a solid base to build on top of.

    Image ; img. After adding the image, we can use some built-in effects from React Konva to add some effects to our images. Blur object to the array. We need the second useEffect callback to apply the filter. It references the imageRef that we set the image to. Then we call imageRef. Resizing images with Transformer In React Konva, transformer objects let users resize images by adding handles to the shape being transformed and resizing as we do with most photo editing apps.

    Adding the transformation feature is a bit complex. Next, we have to add the onTransformationEnd prop with a function that scales the shape by the factor that the user transforms the shape to and set that as the width and height. Besides the shape component, we have to add the Transformer component as a sibling to add the handles to let users transform the shape.

    The onDragEnd handler enables the dragging, as we did in the earlier drag and drop example. The onTransformEnd handler has the function to resize the shape to the new width and height after the user is done dragging. Now we need to allow them to be dropped and added to the Canvas. For that we first need some state to track what all shapes are in the canvas at a given time and their properties like shape type, location, color, etc. We will also need this state in other components in the future like our Inspector component to update the attributes.

    So, we will make this state global.

    Guide to canvas manipulation with React Konva

    Learn more about it. We use nanoid to generate unique keys for each shape and save the x, y values passed along with the type and default values for other visual attributes like width, height, fill and stroke.

    We can do the same for circle and by adding radius instead of width and height. Remember: We set the stringified object payload in our drag start event handler We also need to know the x and y position of the drop event that Konva instance can understand so that we can add the shape at the location of the drop.

    To do that, we need to access the konva instance of the canvas. We can do that by attaching a ref on the Stage component. Now, we can access the konva instance of the canvas at stageRef. To get the correct x and y coordinate of the drop location in the Canvas, we first need to manually set the pointer position in the Konva instance as if the event was raised from within the canvas itself. We can do this by calling setPointersPositions on the Konva instance and passing it the event value.

    Then, we get the derived canvas position back by calling getPointersPositions on the konva instance. Based on the type dragged, we call the createRectangle or createCircle state updater function we created above.

    The Konva.Transformer – a shape with a very particular set of skills

    The offset of the mouse event in relation to the dimensions of the node that was dragged in the palette needs to be considered as well. To make the drop seems seamless and add the node at the exact position where drop events happen, we need to do some offset calculations.

    As mentioned in the diagram above, for rectangles x and y values point to the top-left corner. Therefore, we can directly subtract the offsetX and offsetY values from the x and y values we get back from Konva. Therefore, we first have to calculate the x and y in relation to the mid-point of the node i. Finally we subtract the resultant values from the x and y values we get back from Konva. Then, we iterate over the array to render all the shapes as children of the Layer component.

    We pass the key as id along with all the shape related data as shape prop to the Shape component. Now, we need to create the components that will render the actual shapes in the canvas. Select, Move, Resize and Rotate shapes We start with adding the state update function for selecting and moving shapes. The clearSelection handler sets the selected back to null. A common use case is to remove the middle anchors to reduce UI clutter and show only the corner anchors.

    Border When a transformer is enabled it is useful to show that the focus is not on the transformer. To do this we have the transformer border, with the following properties: borderEnabled: if you prefer not to have a border then set this false and voila — no border! Set this parameter to move the border out slightly — think of it like margin in CSS.

    Setting the borderDash pattern gives a dashed-line effect. Rotation By default the transformer also provides a rotation function. The following properties affect this feature: rotateEnabled: To hide the rotation handle, set this property false. Now the users cannot spin the transformer.

    The default is 50 pixels. The tolerance value is a percentage. If you are using 90 degree snaps, a value of 10 works well.

    Using Konva.js to annotate image with bounding boxes

    Default is around 5 meaning very little snap-jump. Special Features The last two properties give special powers to the transformer. The default value is false.

    What it does is cause the width and height to change proportionally as a corner anchor is dragged. This is often used when hiding middle-anchors using enabledAnchors so as to keep text from being stretched. Transformer, and how to style it. Using a transformer saves a ton of time over any DiY approach you might use as an alternative.


    Konva js transformer events