I am using html5 canvas element to draw a graph with dots denoting various points in here.
I want to display different tool-tip on different points on mouse hover.the text to be displayed as tool-tip will be provided by the user.
I tried but couldn't figure out how to add tool-tip to various points in the graph.The code I'm using for displaying dots is..
// Draw the dots
c.fillStyle = '#333';
for (var i = 0; i < data.values.length; i++) {
c.beginPath();
c.arc(getXPixel(data.values[i].X), getYPixel(data.values[i].Y), 4, 0, Math.PI * 2, true);
c.fill();
}
What addition should I make in this code so that i am able to display user input as tool-tip?
You can display tooltips when your user moves over your chart's data-dot
This tooltip is simply a second canvas which draws the text from the linked textbox and is positions itself above the data-dot.
First you create an array to hold the tooltip info for each of your data-dots.
For each tooltip, you will need:
Here is the code for creating tooltip info to be stored in dots[]
Then you set up a mousemove handler that looks through the dots array. The tooltip is displayed if the user moves inside any data=dot:
[ Edited to fit into your code ]
Here is code and a Fiddle: http://jsfiddle.net/m1erickson/yLBjM/
// unchanged code follows
Short answer: as you've done it now, you can't.
Long answer: you can, but you need to get the exact mouse position every 30milliseconds or so. For each millisecond, you must check if the mouse is hovering over the dot, re-draw the screen and show the tooltip if he's doing it. Doing so by yourself can be tedious, this is why I use gee.js.
Check out this example: http://jsfiddle.net/Saturnix/Aexw4/
This is the expression which controls the mouse hovering:
I tried markE's solution and it worked flawlessly, EXCEPT that when you scroll down just a little bit (e.g. when you have your canvas a little down the site).
Then the positions where your mouseover is recognized will shift to the bottom the same length and it could happen that they end up outside of the canvas and will not be recognized at all...
When you use mouseEvent.pageX and mouseEvent.pageY instead of .clientX and .clientY, you should be fine. For more context, here is my code:
Maybe you could play with the "title" attribute of graph, and adapt its contents depending on the mouse position. Try adding this handler to your fiddle code:
See here: Updated fiddle
Edit: in the code above, I choose to display the tooltip if the mouse is in a square of 10x10 around the point. Of course, this can be adapted. Moreover, there is probably more tests to do, especially before calling the value on getElementById, which could potentially return null.
CSS ONLY method here. No javascript, JQUERY, or special library required. Lightweight, sexy.
HTML
CSS
Here is the fiddle. http://jsfiddle.net/honkskillet/RKnEu/