0

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.

miwalsh
  • 111
  • 2
  • 9
  • Canvas is a bitmap image, and you can not simply add links “into” it. You would either need to position actual HTML `a` elements on top of it, or use a click handler on the canvas element itself and then figure out what action to take based on the coordinates of the click. // Kinda related: http://stackoverflow.com/questions/2932141/does-html5-canvas-have-the-equivalent-of-an-image-map – CBroe Mar 30 '15 at 23:09
  • You can experiment with [Hit regions](https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Hit_regions_and_accessibility). At least that’s what the most modern API suggests—unfortunately it’s barely supported… – Sebastian Simon Mar 30 '15 at 23:09

1 Answers1

1

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.

Keyang
  • 1,828
  • 1
  • 12
  • 17