Align rectangles inside circle - Javascript Canvas

Javascript examples for Canvas:Circle

Description

Align rectangles inside circle

Demo Code

ResultView the demo in separate window

<!--//from   w  w w . j  a va  2 s .c  o  m
Created using JS Bin
http://jsbin.com
Released under the MIT license: http://jsbin.mit-license.org
-->
<html>
   <head> 
      <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.6.6/fabric.js"></script> 
   </head> 
   <body> 
      <canvas id="my-canvas" width="640" height="640"></canvas> 
      <script>
var canvas = new fabric.Canvas(document.querySelector('#my-canvas'));
var circleRadius = 250;
var boxHeight = 30;
var boxWidth = 150;
function createCircleAndBoxes(radius, boxHeight, boxWidth) {
  var circle = new fabric.Circle({
    radius: circleRadius,
    fill: '#f3aa25',
    stroke: '#333'
  });
  canvas.add(circle);

  circle.left = (canvas.width - circle.width) / 2;
  circle.top = (canvas.height - circle.width) / 2;

  var innerCircumference = 2 * Math.PI * (circleRadius - boxWidth);
  var roughBoxCount = Math.floor(innerCircumference / boxHeight);

  var calculatedTop = circle.top + (circle.height / 2) - 1;
  var calculatedLeft = circle.left + (circle.width / 2) + 1;

  var calculatedOriginX = (boxWidth - circleRadius) / boxWidth;
  var calculatedOriginY = (boxHeight / 2) / boxHeight;

  var calculatedAngle = 360 / roughBoxCount;

  for(var i = 0; i<roughBoxCount; i++) {
    var rect  = new fabric.Rect({
        angle: calculatedAngle * i,
        top: calculatedTop,
        left: calculatedLeft,
        centeredRotation: false,
        originX: calculatedOriginX,
        originY: calculatedOriginY,
        width: boxWidth,
        height: boxHeight,
        fill: '#e3e3e3',
        stroke: '#333'
    });
    canvas.add(rect);
  }
}
createCircleAndBoxes(circleRadius, boxHeight, boxWidth);

      </script>  
   </body>
</html>

Related Tutorials