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);
}