To select a shape by id with Konva, we can use the find() method using the # selector. The find() method always returns an array of elements, even if we are expecting it to return one element. if you need only one element you can use findOne() method. The find() method works for any node, including the stage, layers, groups, and shapes.
Instructions: press the “Activate Rectangle” button to select the rectangle by id and perform a transition. You can also drag and drop the rectangle.
<body> <divid="container"></div> <divid="buttons"> <inputtype="button"id="activate"value="Activate rectangle" /> </div> <script> var width = window.innerWidth; var height = window.innerHeight;
var stage = new Konva.Stage({ container: 'container', width: width, height: height });
var layer = new Konva.Layer(); for (var n = 0; n < 10; n++) { var circle = new Konva.Circle({ x: Math.random() * stage.width(), y: Math.random() * stage.height(), radius: Math.random() * 50 + 25, fill: 'red', strokeWidth: 3, stroke: 'black' });
layer.add(circle); }
var rect = new Konva.Rect({ x: 300, y: 90, width: 100, height: 50, fill: 'green', strokeWidth: 3, offset: { x: 50, y: 25 }, draggable: true, id: 'myRect' });
layer.add(rect); stage.add(layer);
var tween;
document.getElementById('activate').addEventListener( 'click', function(){ // or var shape = stage.findOne('#myRect'); var shape = stage.find('#myRect')[0];