Get the width and height of a moving figure when clicking on it? - Javascript Canvas

Javascript examples for Canvas:Mouse

Description

Get the width and height of a moving figure when clicking on it?

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="https://code.jquery.com/jquery-1.8.3.js"></script> 
      <script type="text/javascript">
    $(window).load(function(){/*  ww  w  .j  a va2s. c o m*/
    var color = ['green', 'red', 'blue', 'purple', 'yellow'];
    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");
    var posicion = 0;
    var tamano = 0;
    setInterval(function () {
    ctx.clearRect(0, 0, 400, 400);
    ctx.fillRect(posicion, 0, tamano, 400-tamano);
    posicion++;
    tamano++;
    if (posicion > 400){
        posicion = 0;
        tamano = 0;
        ctx.fillStyle = color[Math.floor(Math.random() * 4)];
        }
    }, 30);
    $("#canvas").click(function(e){
        var cRect = canvas.getBoundingClientRect();
        var mouseX = e.clientX - cRect.left;
        var mouseY = e.clientY - cRect.top;
        var figureX = posicion;
        var figureY = 0;
        var figureW_off = posicion + tamano;
        var figureH_off = 400-tamano;
        ctx.fillStyle = color[Math.floor(Math.random() * 4)];
        if(mouseX >= figureX && mouseX <= figureW_off &&
          mouseY >= figureY && mouseY <= figureH_off)
          $("p").text( "The Width of the figure is " + tamano+ " and the Height is " + (400-tamano));
    });
    });

      </script> 
   </head> 
   <body> 
      <canvas id="canvas" width="400" height="400" style="border:1px solid #000000"></canvas> 
      <p id="texto"></p>  
   </body>
</html>

Related Tutorials