yanyusanqian
yanyusanqian

Reputation: 120

konvaJS : How can I add a custom Tag to distinguish shapes?

I draw a line to connect two rect base on mouse move. I want a rect to be connected only once.I have an idea that is to record the id of two rect with separator then store in the id of lines. But when the mouse moves, the array of shapes on this layer will cycle once. It's extremely inefficient. So I want to ask if there are any way taht i can add a custom tag in those shape to distinguish them. Like rect.isLinked = true/false. I didn't find this method in the API documentation.

Any one can help me? Thanks!

Upvotes: 1

Views: 384

Answers (1)

Vanquished Wombat
Vanquished Wombat

Reputation: 9525

Objectively, this is a requirement to hold a list of things with some value, and be able to efficiently lookup an instance in the list. It is a standard javascript pattern

Create a plain object

let myList = {};

We can refer to object properties as strings, so to store a value we can use:

myList["shapeId1"] = "I am linked";

And now we can check if shapeId1 is linked by testing for the presence of a property with that string name in the list.

let isLinked = myList.hasOwnProperty("shapeId1"); // true if property exists, false if not.

You can extend this to store more complex values - what if we need to know the id of the linked shape.

let myList = {};
...
myList["shapeId1"] = {linkedTo: "shapeId2"};
myList["shapeId2"] = {linkedTo: "shapeId1"};
...
console.log("ShapeId1 is linked = " + myList.hasOwnProperty("shapeId1")); // true
if (myList.hasOwnProperty("shapeId1")){
    console.log("ShapeId1 is linked to " + myList["shapeId1"].linkedTo); // shapeId2
}
etc

Regarding how to deploy this with Konva - you can assign an id value to a shape when it is created, just as you would assign, say, the fill colour. If you wanted to highlight the shapes at both ends of your line link you could use the Konva find or findOne method to get the shapes via their id.

Upvotes: 2

Related Questions