Search code examples
javascripthtmlhtml5-canvas

How do you draw a picture of a square inscribed in a circle with radius R?


Is there any way you would draw a square inscribed a circle, with the square’s corners tangent to the circumference of the circle and having radius R? It should look something like the image attached. Of course, the rectangle is supposed to be square.

Here is what I have so far:

function draw() {
  const canvas = document.getElementById('circle');

  if (canvas.getContext) {
    const ctx = canvas.getContext('2d');
    const X = canvas.width / 2;
    const Y = canvas.height / 2;
    const R = 50;
    const angle = 45 * (Math.PI / 180);
    const G = Math.sin(angle) * R;

    ctx.beginPath();
    ctx.arc(X, Y, R, 0, 2 * Math.PI, false);
    ctx.lineWidth = 2;
    ctx.strokeStyle = '#0000FF';
    ctx.stroke();
  }
}
canvas {
  position: absolute;
  height: 250px;
  width: 250px;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
<body onload="draw()">
  <div style="text-align:center;" , style="position: absolute">
    <canvas id="circle" width="150" height="150"></canvas>
  </div>
</body>

enter image description here


Solution

  • One approach would be to make the circle fit the canvas dimensions, then calculate accordingly, to get the variables for the circle and the square. The canvas is a square so I don't see why we would need two different variables for the height and width. canvas.width = canvas.height so we can just use canvas.width to do all of the calculations.

    enter image description here

    function draw() {
      const canvas = document.getElementById('circle');
      if (canvas.getContext) {
        const ctx = canvas.getContext('2d');
        
        // Circle
        const r = canvas.width/2,
              angle = 45*(Math.PI/180),
              g = Math.sin(angle)*r;
    
        drawCircle(canvas.width, r);
    
        function drawCircle(diameter, radius){
          ctx.beginPath();
          ctx.arc(diameter/2, diameter/2, radius, 0, 2 * Math.PI, false);
          ctx.lineWidth = 2;
          ctx.strokeStyle = '#0000FF';
          ctx.stroke();
        }
    
        // Square  
        const squareWidth = Math.sqrt(2*r**2),
              startX = (canvas.width - squareWidth) / 2,
              startY = startX;
        
        drawSquare(startX, startY, squareWidth);
    
        function drawSquare(x, y, width){
          ctx.beginPath();
          ctx.rect(x, y, width, width)
          ctx.stroke();          
        }
      }
    }
    canvas {
      position: absolute;
      height: 150px;
      width: 150px;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }
    <body onload="draw()">
      <div style="text-align:center;" , style="position: absolute">
        <canvas id="circle" width="150" height="150"></canvas>
      </div>
    </body>