你如何画一个正方形内切在半径为 R 的圆上?

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

有什么方法可以画一个内接圆的正方形,正方形的角与圆的周长相切,半径为 R?它应该看起来像附加的图像。当然,矩形应该是正方形。

这是我目前的情况:

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>

请将此添加到您的绘制函数中:

            const cos45 = 0.7071;
            // squareSide = cos45 * R * 2;
            const halfOfSquareSide = cos45 * R;
            ctx.beginPath();
            ctx.rect(X - halfOfSquareSide, Y - halfOfSquareSide, halfOfSquareSide * 2 , halfOfSquareSide * 2);
            ctx.lineWidth = 2;
            ctx.strokeStyle = '#FF0000';
            ctx.stroke();

一种方法是使圆适合 canvas 尺寸,然后进行相应计算,以获得圆和正方形的变量。 canvas 是一个正方形,所以我不明白为什么我们需要两个不同的高度和宽度变量。 canvas.width = canvas.height 所以我们可以使用 canvas.width 来完成所有的计算。

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>