Search code examples
html5-canvasmouseeventkineticjs

HTML 5 Canvas Mouse over event on element (show tooltip)


I am working on a visualization project. Based on my data I am plotting hundreds of small circle on canvas. I want to add a mouse over event so that whenever a mouse is the enclosing area of a circle it will show some node property from my data as a tool tip or as text on the canvas. My current drawCircle method

function drawCircle(canvas,x,y,r) 
{
    canvas.strokeStyle = "#000000";
    canvas.fillStyle = "#FFFF00";
    canvas.lineWidth = 2;
    canvas.beginPath();
    canvas.arc(x,y,r,0,Math.PI*2,true);
    canvas.stroke();
    canvas.fill();
    canvas.closePath();
}

I have looked into kinetic.js But can't figure it out how I can call my drawCircle [repetitively] method using their library.

Any help will be highly appreciated.


Solution

  • If you still want to use KineticJS, you would put the Kinetic shape stuff inside your drawCircle routine. This is basically pulled out of their tutorial and stripped down:

    function drawCircle(stage,x,y,r) {
      var circle = new Kinetic.Shape(function(){
        var context = this.getContext();
        // draw the circle here: strokeStyle, beginPath, arc, etc...
      });
      circle.addEventListener("mouseover", function(){
        // do something
      });
      stage.add(circle);
    }
    

    If you don't want to use KineticJS after all, you will need to remember for yourself the positions and radii of every circle you drew, and then do something like this:

    canvas.onmouseover = function onMouseover(e) {
      var mx = e.clientX - canvas.clientLeft;
      var my = e.clientY - canvas.clientTop;
      // for each circle...
      if ((mx-cx)*(mx-cx)+(my-cy)*(my-cy) < cr*cr)
        // the mouse is over that circle
    }