Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select lines that are drawn on a HTML5 Canvas?

I am using using HTML5 Canvas to plot lines. A single line is formed by calling drawLine() on multiple intermediate points. For example:

(0,0) -> (10, 10) -> (10, 5) -> (20, 12)

would show up as one line on the plot.

All the (x,y) co-ordinates of a line are stored in an array.

I want to provide the users with the ability to select a line when they click on it. It becomes difficult to do this in HTML5 Canvas as the line is not represented by an object. The only option that I am left with is to first find that (x,y) coordinate of any line that is closest to the (x,y) of a mousedown event. Once I detect which line the user has selected, then I need to redraw the line with a bold color or put a translucent color around it. But, I am assuming that this would be too time-intensive, as it involves looping over all (x,y) coordinates of all lines.

I am looking for ways that can help me achieve the above in a more time-efficient manner. Should I consider using SVG in HTML5?

Any suggestions would be appreciated.

like image 557
kkonweb Avatar asked Nov 18 '11 15:11

kkonweb


People also ask

What is used to draw lines on the canvas?

Overview. The lineTo method is used to draw a line on the canvas. Below are the steps to draw a line on the canvas: Use the beginPath() method to start a new path.

What is drawing lines in HTML?

Draw Lines To draw a line using HTML5 Canvas is simple, just like draw a line on a paper, define a path, and then fill the path. See the following steps : Resets the current path using beginPath() method. Let move the drawing cursor to start point to create a new subpath using moveTo(x,y) method.

Which built in HTML5 object is used to draw on the canvas?

The HTML <canvas> element is used to draw graphics, on the fly, via JavaScript. The <canvas> element is only a container for graphics. You must use JavaScript to actually draw the graphics. Canvas has several methods for drawing paths, boxes, circles, text, and adding images.


1 Answers

I think you'd find this much easier in SVG. There each line would be a <polyline> and you could add a onclick handler to do what you want. For example...

<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
    <polyline points="20,20 40,25 60,40 80,120 120,140 200,180" 
              style="fill:none;stroke:black;stroke-width:5"
              onclick="this.style.stroke='red'" />
</svg>
like image 189
Robert Longson Avatar answered Oct 02 '22 11:10

Robert Longson