This piece of code creates rectangles every time the canvas is clicked on. Each rectangle object is then pushed into an array. I would like each rectangle created being able to return its own array index when clicked on.
What do I want to achieve with this?
My idea a software with GUI that allows creating modules/nodes with input and output ports and connect them with wires (like Max/MSP, Pure Data, Quartz Composer, Reaktor, NodeRed, etc.). In order to be able to connect the modules with each other, they need to be able to return their own ID so a function external to the modules can connect them.
var width = window.innerWidth - 50;
var height = window.innerHeight - 100;
var rectArray = [];
var stage = new Konva.Stage({
container: 'container',
width: width,
height: height
});
var layer = new Konva.Layer();
stage.add(layer);
var clickRect = new Konva.Rect({ // clickable background
x: 0,
y: 0,
width: width,
height: height,
stroke: 'black',
strokeWidth: 2,
listening: 'true'
})
layer.add(clickRect);
var text = new Konva.Text({ //text to display info
x: 10,
y: 10,
fontFamily: 'Calibri',
fontSize: 24,
text: '',
fill: 'black'
});
clickRect.on('click', function() { /// here we create a module
var newRect = new createModule();
rectArray.push(newRect);
});
function createModule() {
var mouseX = stage.getPointerPosition().x;
var mouseY = stage.getPointerPosition().y;
var rect = new Konva.Rect({
x: mouseX,
y: mouseY,
width: 50,
height: 50,
stroke: 'black',
strokeWidth: 2,
draggable: true
});
rect.on('click', function(evt) {
alert("clicked");
})
text.setText(rectArray.length + 1);
layer.add(text);
layer.add(rect);
stage.add(layer);
}
stage.draw(); // draw so we can see click rect.
<script src="https://cdn.rawgit.com/konvajs/konva/1.7.6/konva.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container"></div>
<p id="display1">-</p>