miwalsh
miwalsh

Reputation: 111

HTML5 JavaScript Anchor for Bar Chart Element

I'm creating an HTML5 page for my application that uses the standard canvas for drawing a bar graph, and I'd like to have each one of the bars in the chart to have a hyperlink to drill down into more data. I know that this is probably a simple question, but I'm not familiar with JavaScript enough to have the answer readily available. I'm drawing the bar chart pieces in two parts, once filling the entire area and then removing the "already completed" part, as such:

context.fillRect( elements[i][0], edgeOfChart, offset, 250 )
context.clearRect( elements[i][0], edgeOfChart, offset, 250.0 - heightComplete )

How can I add an anchor for a click/touch-through?

Thanks.

Upvotes: 0

Views: 228

Answers (1)

Keyang
Keyang

Reputation: 1878

To interact with Canvas is bit of pain. Same as canvas in other technologies, you have to handle the mouse/touch events in elements and calculate the position of your bar charts to find out if user is clicking it or not. e.g. in your example, you have a rect with following coords elements[i][0], edgeOfChart, offset, 250

if user clicked on you need add a onclick event listener to canvas, the callback function will send you a parameter with "event object" (see http://www.w3schools.com/jsref/dom_obj_event.asp) with which you can get the X and Y coords where the mouse is clicked.

Then you could figure out if the clicked coord is in the bar or not.

To build interactive chart, a suggested way to use is SVG which is element based and each element could have their own event handler. Take a look at SVG for details.

Upvotes: 1

Related Questions