KineticJS: Issue with JSON saving - Objects are being duplicated during the save process

Major Revision

After assessing my current situation, it appears to be another puzzle or scenario, specifically related to saving to json in a broader context.

To illustrate, I include a new Shapegroup to a layer on the stage by utilizing the following code snippet:


...
var selectedShape, json = null;
...
function addNode(xPos, yPos) {
    //create the new node
    var node = new Kinetic.Circle({
        id: 'myRect',
        x: xPos,
        y: yPos,
        radius: 30,
        fill: '#FFFFFF',
        stroke: '#000000',
        strokeWidth: 4,
        // test: "testattr"
    });

    // create the label
    var label = new Kinetic.Text({
        x: node.getX() - node.getRadius() + 10,
        y: node.getY() + node.getRadius() + 4,
        text: 'node',
        fontSize: 12,
        fontFamily: 'Arial',
        fill: 'black',
    });

    // create group
    var nodeGroup = new Kinetic.Group({
        draggable: true
    });

    // add shapes to group
    nodeGroup.add(node);
    nodeGroup.add(label);

    // add group to the layer
    layer.add(nodeGroup);

    // add layer to the stage
    stage.add(layer);

    /*
    * Event Handlers for Nodes
    */
    
    // Additional events ...

}

Introducing a button labeled 'add new State' which essentially appends a new group. Here is the associated code:


$('#createNode').click(function(e){
    addNode(125, 125);
});

Furthermore, there's a button called "remove State" that deletes a chosen nodegroup when clicked. The corresponding code is as follows:


$('#removeNode').click(function(e){
    if(selectedShape){
        var selectedGroup = selectedShape.getParent();
        selectedGroup.removeChildren();
        selectedGroup.remove();
        layer.draw();
    } else {
        writeMessage(messageLayer, 'No Object chosen');
    }
});

Additionally, there's a 'save to json' button intended to store all remaining Shapes on the Stage:


$('#saveJSON').click(function(e){
    json = null;
    json = stage.toJSON();
    console.log(json);
});

Testing various scenarios including saving an empty stage, adding nodes and saving again reveal discrepancies with doubled objects.

Conclusion: Issues seem to stem from the addNode function where different layers are involved. Seeking guidance on better practices for working with shapegroups within a single layer in KineticJS.

Answer №1

Upon reflecting on my initial question, rewriting it for clarity, and conducting further investigation, I have successfully discovered the root of my issue. Allow me to share my findings with you:

During the addnode functionality, I erroneously utilized stage.add(layer), which resulted in the undesired behavior outlined in my original question.

I have since rectified this by relocating stage.add(layer) from addNode to my init() function, which is only called during initialization. In addNode, I now simply use

layer.add(nodeGroup); layer.draw()
; resulting in a successful resolution. I apologize for any inconvenience caused; I had encountered a mental block that has now been cleared.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Add styling to a window popup and close it when focus is lost in Ext JS

I am trying to implement a specific functionality where the popup arrow should be at the edge of the textbox as shown in the image below. How can I achieve this? Additionally, how can I make sure that clicking outside the control destroys the popup instead ...

Submitting Data Forms with AJAX on dynamically loaded webpages

Issue with Form Submission in Ajax-Generated Page I am experiencing an issue with form submission on a page generated within AJAX. The page contains two forms, #form1 and #form2. The jQuery code for submitting the form is as shown below: jQuery("#form1" ...

Strange anomalies arising in frontend Apollo and GraphQL integration

Currently, I am working with nuxt.js and apollo. One issue I am facing is that when I click a button, it sends a request to the graphql server. The strange part is that the first time I click the button, everything works as expected. However, when I clic ...

Error occurred due to an improperly formatted authorization header while attempting to upload an object to S3 using the JavaScript SDK

When attempting to upload an object to Amazon S3 using their JavaScript SDK, I encounter the following error message: <Error> <Code>AuthorizationHeaderMalformed</Code> <Message>The authorization header is malformed; the reg ...

Google Feed API - Retrieving saved data from RSS feed cache

We have implemented the Google Feed API to display our latest blog posts on our website. However, even after 24 hours, our most recent post is still not appearing on our site. Despite confirming that the RSS feed contains the newest content, it seems that ...

What triggers the onmouseout event to occur?

Is the event triggered continuously whenever the mouse is not hovering over the element? Or is it a one-time action when the mouse exits the element? This distinction is crucial for me to determine when the mouse pointer leaves the element, while only wa ...

Tips for effectively utilizing props in react

Within one of my components named header, there is a button that I want to use to toggle the visibility of the navbar component. To achieve this, I attempted to create a prop in the main component below which houses all the other components including heade ...

The mystery of Wordpress AJAX: why does it always return 0 for logged-out users?

I've run into a puzzling issue with my Wordpress site's member directory. Using Ajax, I can successfully display and alphabetically sort member profiles when logged in, but the functionality breaks when logged out, returning '0'. Despit ...

What is the reason for memory allocation only occurring when geometry.elementsNeedUpdate is used?

When using a basic animate function like this: function animate() { geometry.elementsNeedUpdate = true; requestAnimationFrame( animate ); renderer.render( scene, camera ); } A memory allocation occurs even if no elements are changed. To address this, I ...

Looking to obtain rendered tree data upon page load?

Is there a way to retrieve all rendered tree metadata when the page loads using jstree? I'm looking for an output similar to this: [23,24] Please note that I would like to have each id stored in the metadata object displayed as [23,24] upon page loa ...

"Utilize Jersey's ClientResponse.getObject method to extract data of any given

I encountered an issue with deserialization while using the Jersey ClientResponse.getEntity method. Despite following various tutorials and resources, such as: The exception persists despite my efforts to address it repeatedly. My objective is to avoid: ...

Activate the drop-down division when the search box is in focus with xoxco technology

Currently, I am incorporating Xoxco's tag input plugin which can be found at the following link: In my customization, I have implemented JQuery's focus() function <input id="tags_1" class="tag-holder" type="text" class="tags" /></p> ...

The JSON array successfully retrieves the data, however, it is unable to be formatted and displayed

I am having trouble displaying JSON data from an online source in my app. Although the data is being retrieved successfully, it does not appear on the activity where it should be displayed. I suspect there might be an issue with how I am populating the lis ...

Navigating discreetly with invisible scroll bar

I am attempting to design a webpage where the scroll bar is hidden, but users can still scroll or click on links to navigate down the page. I have managed to hide the scroll bar, but I am facing an issue where the page jumps to 100% when scrolling. How can ...

Error 431 is encountered when submitting an Axios post request

Facing a 431 (Request Header Fields Too Large) error when trying to submit a form in my single-page project through an axios request. I've attempted setting maxContentLength and maxBodyLength to Infinity, as well as adding max-http-header-size in the ...

Preserving the <script> tag when defining HTML code

During an AJAX call, I am receiving plain HTML with some JavaScript code. When I try to display this response in a container using .html (jQuery) or innerHTML (plain JavaScript), it removes the <script> tag and all JavaScript code. However, when I c ...

How can I send an object array that includes both data and files via ajax, and then access it in an MVC controller?

I currently have an object array structured as follows: var array=[ { Name:"name", Address:"address", Files://array of files }, { Name:"name", Address:"address", Files://array of files } ]; I am trying to pass this array through a ...

Looking for assistance with overriding kendo UI validation requirements

I'm looking to customize the date validation in my code to validate the date as DD/MM/YYYY. Here's my current code snippet and I'm getting an error message that says: Unable to get property 'methods' of undefined or null referen ...

Tips for having <script> update onchange instead of just onload

Is there a way to update the output of the <table id="mortgagetable"> each time a user changes the input values in the form? Currently, it only updates on load. Additionally, the content of the <div id="years" style="display:inline-block;">25 ...

The npm audit tool uncovers unexpected dependencies in your project

When running npm audit, I receive warnings along with strange dependencies in the form of random hexadecimal strings. These strings change every time I run npm audit and are the same for all packages mentioned in the audit report. How can I remove these o ...