I wrote this code to draw random graphs. I have been trying in vain to find how I can select a line in the graph so that I can apply the prim's algorithm as one selects lines and see if they have found the minimum tree.
function draw(n,rep){
var cvs=document.getElementsByTagName('canvas')[0];
/**
* @type CanvasRenderingContext2D
**/
var ctx=cvs.getContext('2d');
ctx.beginPath();
var randomX=[];
var randomY=[];
ctx.lineWidth=2;
ctx.font = '3'+' Arial';
var weights=[];
var lastRandomx=Math.random()*200;
var lastRandomy=Math.random()*200;
for (var i = 0; i <n ; i++) {
var cwidth = cvs.width;
var cheight = cvs.height;
randomX[i] = Math.random()*cwidth*2/3;
randomY[i] = Math.random()*cheight*2/3;
weights[i]=Math.round(Math.random()*20);
ctx.fillRect(randomX[i],randomY[i],5,5);
ctx.moveTo(lastRandomx,lastRandomy);
ctx.lineTo(randomX[i],randomY[i]);
lastRandomx=randomX[i];
lastRandomy=randomY[i];
}
for (var i = 0; i < rep; i++) {
var rand=Math.round(rep*Math.random());
ctx.lineTo(randomX[rand],randomY[rand]);
}
ctx.closePath();
ctx.stroke();
};
I found this in stackoverflow and it doesn't help much. How to select lines that are drawn on a HTML5 Canvas?. I was wondering if there's a prewritten code so that I need not write it from scratch.
I was thinking if I could find the location of the mouse as it moves and each time check to see if the location of mouse is on the line as in here Finding if a point is on a line. Please help and suggest if there's any prewritten code because I'm restricted by time. Thank you in advance.
You can use math to determine which line is closest to the mouse.
Here's example code and a demo: