Render JSON data onto canvas using AJAX and save the JSON elements into variables

Hey there! I've written a code snippet to retrieve JSON data from a text file and use it to draw shapes on a canvas. At this point, the shapes are successfully drawn on the canvas, but now I aim to store each shape as a variable for future reference when a user interacts with them.

I attempted to achieve this by writing some more code, however, I've encountered an issue - only one rectangle is being drawn and the text inside it is not appearing as expected.

Let's take a look at my code...

function ajax_GetCanvasData(){
    var req = new XMLHttpRequest();
    var context = document.getElementById("drawing_canvas").getContext('2d');

    req.open("GET", "List.php", true);
    req.setRequestHeader("Content-type", "application/json");
        req.onreadystatechange = function() {
        if(req.readyState == 4 && req.status == 200) {
            var data = JSON.parse(req.responseText);

            for(var item in data){
                if (data[item].type == "Node"){

                    var text = data[item].text;
                    var cx = data[item].cx;
                    var cy = data[item].cy;
                    var width = data[item].width;
                    var height = data[item].height;
                    var colour = data[item].colour;

                    node = new nodeObj(context,text,cx,cy,width,height,colour);
                }

            }
        }
    }
    req.send(null);
}

function nodeObj(context,text,cx,cy,width,height,colour) {

    this.text = text;
    this.cx = cx;
    this.cy = cy;
    this.width = width;
    this.height = height;
    this.colour = colour;

    var lineheight = 15

    context.fillStyle = colour;
    context.fillRect(cx,cy,width,height);
    context.strokeRect(cx,cy,width,height);

    context.fillStyle = '#000000';
    context.font = 'bold 12px Ariel, sans-serif';
    context.textAlign = 'center';
    context.textBaseline = 'ideographic';
    wrapText(context, text, cx + (width*0.5), cy+(height*0.5), width, lineHeight);
}

Answer №1

If you're looking to manipulate objects drawn on a canvas programmatically, I suggest checking out the library called paper.js. With paper.js, you can keep track of object references in the form of paths and easily make changes to them later on.

This could be exactly what you need for your project.

For more information and a helpful guide on how to use paper.js, take a look at this screencast I put together: . It's a great resource to get started with what you have in mind.

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

The Mongoose server unexpectedly shut down

We encountered a server issue while working on our movie database project. After deleting and rewriting the code, we ran into a problem. Here is the advice given by our instructor: Troubleshooting mongoose.connect errors If you are facing a connection ...

Using node.js to send custom data over a websocket

I came across an excellent tutorial on websockets. In this tutorial, the server decodes and writes a message to the console whenever it receives a message from the client. After that, the server sends the message back to the client. var firstByte = data ...

What's causing ng-show to malfunction in IE11 on AngularJS?

I am experiencing a strange issue with my code - ng-show works perfectly fine on Firefox, but not on IE 11. <div ng-show="isExist" class="panel panel-default"> Here is the relevant code snippet from the controller: $scope.isExist = false; if(user ...

MasteringNode: Exercise 3 The Beginning of My Journey with Input and Output

While working in Visual Studio Code on Windows 10 using powershell.exe as my terminal, I encountered a problem that I couldn't solve on my own. After numerous attempts, I decided to search the internet for a solution, and here's what I found: v ...

Use JavaScript to dynamically populate dropdown list options with array elements

I attempted to populate a dropdown list with array elements using javascript, but I encountered issues. I referred to the following links for assistance: JavaScript - populate drop down list with array use a javascript array to fill up a drop down se ...

Error encountered in Angular CLI: Attempting to access property 'value' of an undefined variable

I am encountering an issue while trying to retrieve the values of radio buttons and store them in a MySql database. The error message I receive is TypeError: Cannot read property 'value' of undefined. This project involves the use of Angular and ...

Converting API data in Angular using rxjs

Hey there, I received this response from an API: { "records":[ { "id":1, "motivazione":"", "autorizzazione":false, } ] } Can anyone help me transform it to loo ...

Is there a way to automatically activate the loader function once the form has been submitted?

Currently, I am in the process of developing a simple journaling application inspired by Journalisticapp.com. My main goal is to enhance my knowledge and skills in React and React Router. The Entries component will display a list of journal entries fetche ...

Synchronizing Duplicate Instances of an Object in AngularJS

Imagine a scenario where our database consists of the following relationships: A Company, which can have multiple employees An Employee is employed by only one Company An Employee can also manage other employees ...and these entities in the database: ...

Fetch a document from a NodeJS Server utilizing Express

Is there a way to download a file from my server to my machine by accessing a page on a nodeJS server? I am currently using ExpressJS and I have attempted the following: app.get('/download', function(req, res){ var file = fs.readFileSync(__d ...

Strangely, the quirks of the .hover() function on iOS

I'm finding it puzzling why .hover() is acting differently on iOS. On my desktop, I have a portfolio gallery with images that link to individual pages of my work. When hovering over an image, it slightly fades and a title animates in. However, when I ...

"Enhancing the Today Button in FullCalendar with Custom Functionality

My issue lies with the implementation of fullCalendar. Specifically, I am utilizing the week view (defaultView: 'basicWeek') with the toolbar buttons for 'today', 'prev', and 'next'. The problem arises when I click t ...

What classifies jqXHR as "unsuccessful"?

I have encountered an issue with my ajax request to a spring security backend. It seems that the .then function never gets triggered for some reason. Strangely, the .fail function gets executed on every request, even though the request goes through seamles ...

Angular testing does not recognize the variable

I'm currently testing an Angular app in Protractor and I'm puzzled by a certain issue that keeps occurring. Here's the test code snippet: beforeEach(function() { browser.get('http://localhost:8080/#/'); ... ...

React: Remove a particular row from the table

I am currently working on a project that involves building a table component. Each row in this table is also a separate component. class FormulaBuilder extends Component { constructor(props) { super(props); this.state = ...

Encountered an issue while trying to use Figma's spellchecker extension

Despite following the instructions in the readme carefully, I am facing difficulties running the Figma spellchecker extension. Executing npm run build goes smoothly. But when I try to run npm run spellcheck, I encounter an error message in the console: co ...

The variable `req.session.secret` is not defined within the routes that utilize express-session

I'm currently working on a simple application that utilizes an express session. In my entry script, I initialize the session as follows: export const app = express(); export const server = Server(app); app.use(bodyParser.urlencoded({ extended: false ...

When utilizing both text and file in a request, the Laravel filebag array remains unfilled

I'm having trouble uploading an image and text using ajax to my laravel server. I can't figure out how to include the File in the ajax request. I've attempted creating a FormData object and adding the necessary params, as well as serializin ...

Is it possible to store dat.gui presets for controls that are dynamically added?

I have a dynamic dat.gui interface where I add controls, but the "save settings" feature doesn't seem to recognize them. var mygui = new dat.GUI(); mygui.remember(mygui); // Example of adding a control in the standard way mygui.control1 = 0.0; var c ...

Displaying image behind bootstrap modal using Lightgallery js

Can anyone help me with an issue I'm having with previewing images using lightgallery js? The image is showing up behind the modal window. https://i.sstatic.net/FncZB.png I'm not sure why this is happening Here's the javascript code I am ...