draw polygon shape on canvas and allow tooltip on it - Javascript Canvas

Javascript examples for Canvas:Shape

Description

draw polygon shape on canvas and allow tooltip on it

Demo Code

ResultView the demo in separate window

<!doctype html>
<html>
   <head> 
      <!-- reset css --> 
      <script type="text/javascript" src="https://code.jquery.com/jquery.min.js"></script> 
      <style>

body{ background-color: ivory; }
#canvas{border:1px solid red;}

      </style> 
      <script>
$(function(){/*from   w  w w .  j  a  v  a2  s .c  o  m*/
    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");
    var $canvas=$("#canvas");
    var canvasOffset=$canvas.offset();
    var offsetX=canvasOffset.left;
    var offsetY=canvasOffset.top;
    var scrollX=$canvas.scrollLeft();
    var scrollY=$canvas.scrollTop();
    var $results=$("#results");
    // create an object holding all polygon points
    var triangle=[{x:100,y:50},{x:150,y:100},{x:50,y:100}];
    // draw the polygon
    define(triangle);
    ctx.fill();
    // define the polygon
    function define(polygon){
        ctx.beginPath();
        ctx.moveTo(polygon[0].x,polygon[0].y);
        for(var i=1;i<polygon.length;i++){
            ctx.lineTo(polygon[i].x,polygon[i].y);
        }
        ctx.closePath();
    }
    function hitTest(polygon){
        define(polygon);

        return(ctx.isPointInPath(mouseX,mouseY));
    }
    function handleMouseMove(e){
      e.preventDefault();
      mouseX=parseInt(e.clientX-offsetX);
      mouseY=parseInt(e.clientY-offsetY);
      // check if the mouse is inside the polygon
      var isInside=hitTest(triangle);
      if(isInside){
          $results.text("Mouse is inside the Triangle");
      }else{
          $results.text("Outside");
      }
    }
    $("#canvas").mousemove(function(e){handleMouseMove(e);});
}); // end $(function(){});

      </script> 
   </head> 
   <body> 
      <p id="results">Hit results</p> 
      <canvas id="canvas" width="300" height="300"></canvas>  
   </body>
</html>

Related Tutorials