Reputation: 1651
I have a project regarding the Dijkstra's algorithm with a canvas to draw the graph. I have the following code in the JavaScript of my html file. This is a portion of JavaScript code.
var graph = {};
var i = 0;
function ondblclick(e)
{
var cell = getpos(e)
canvasX = cell.x-10;
canvasY = cell.y-10;
graph = {i: {coord : [cell.x,cell.y]}};
var g_canvas = document.getElementById("canvas");
var context = g_canvas.getContext("2d");
var cat = new Image();
cat.src = "dot1.png";
cat.onload = function()
{
context.drawImage(cat,canvasX , canvasY);
}
}
i = i+1
function submit()
{
for (i = 0; i<= 5; i = i + 1)
alert(graph.i.coord);
}
here I have a canvas and the 'ondblclick' is the function when the user double clicks on the canvas. Canvas is used to draw nodes and edges. 'ondblclick' is used for drawing the nodes.
My issue is on saving the coordinate values of the nodes to the 'graph' in dictionary format. it accepts only the last value. How can I update/append/extend the all values to the same dictionary using the variables I and cell.x,cell.y values??
Upvotes: 2
Views: 312
Reputation: 10636
You nearly had it.
var graph = [];
function ondblclick(e)
{
var cell = getpos(e)
canvasX = cell.x-10;
canvasY = cell.y-10;
graph.push({coord : [cell.x,cell.y]});
var g_canvas = document.getElementById("canvas");
var context = g_canvas.getContext("2d");
var cat = new Image();
cat.src = "dot1.png";
cat.onload = function()
{
context.drawImage(cat,canvasX , canvasY);
}
}
function submit()
{
for (i = 0; i<= 5; i = i + 1)
alert(graph[i].coord);
}
In order to get data into graph
you need to push objects into an array, then loop through that array. Your problem was that you used the i
variable incorrectly, thus storing (and retrieving) your coords ontop of each other.
Upvotes: 1
Reputation: 328614
A dictionary (key-value store) is the wrong data structure for a graph. Use an array where you can append nodes. Use a dictionary for each element in the array to save coordinates in them.
Upvotes: 0