Calculate the bounding box's X, Y, Height and Width of a rotated element via JavaScript - Javascript Canvas Reference

Javascript examples for Canvas Reference:rect

Description

Calculate the bounding box's X, Y, Height and Width of a rotated element via JavaScript

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.10.1.js"></script> 
      <script type="text/javascript">
    $(function(){// w  w  w .j  av  a  2s.  c o m
$(function() {
   var lienzo = document.getElementById('lienzo'),
   contexto = lienzo.getContext('2d'),
   rotador = new Rotador(),
   contenedor = new Contenedor();
   (function drawFrame() {
      contexto.clearRect(0,0,lienzo.width, lienzo.height);
      window.requestAnimationFrame(drawFrame, lienzo);
      rotador.draw(contexto);
      contenedor.draw(contexto, rotador);
   })();
});
function Rotador() {
   this.x = lienzo.width/2;
   this.y = lienzo.height/2;
   this.w = 250;
   this.h = 20;
   this.angulo = 0;
   this.factor = 0;
}
Rotador.prototype.draw = function(contexto) {
   contexto.save();
   contexto.translate(this.x, this.y);
   if((Math.round( this.factor * 10 ) / 10) == 2.0) this.factor = 0;
   this.factor += 0.003;
   this.angulo = Math.PI * this.factor;
   contexto.rotate(this.angulo);
   contexto.beginPath();
   contexto.rect(-(this.w/2), -(this.h/2), this.w, this.h);
   contexto.stroke();
   contexto.restore();
}
function Contenedor() {
   this.x = lienzo.width/2;
   this.y = lienzo.height/2;
   this.angulo = 0;
   this.w = 0;
   this.h = 0;
}
Contenedor.prototype.draw = function(contexto, rotador) {
   contexto.save();
   contexto.translate(this.x, this.y);
   contexto.beginPath();
   contexto.strokeStyle = '#E24B4B';
   this.angulo = ((rotador.angulo > Math.PI * 0.5 && rotador.angulo < Math.PI * 1) || (rotador.angulo > Math.PI * 1.5 && rotador.angulo < Math.PI * 2))? Math.PI - rotador.angulo : rotador.angulo;
   this.w = Math.sin(this.angulo) * rotador.h + Math.cos(this.angulo) * rotador.w;
   this.h = Math.sin(this.angulo) * rotador.w + Math.cos(this.angulo) * rotador.h;
   contexto.rect(-(this.w/2), -(this.h/2), this.w, this.h);
   contexto.stroke();
   contexto.restore();
}
    });

      </script> 
   </head> 
   <body> 
      <canvas id="lienzo" width="400" height="400" style="background-color:#ccc;"></canvas>  
   </body>
</html>

Related Tutorials