Search code examples
canvashtml5-canvas

HTML5 Canvas circle inside circle


enter image description here

Trying to build this using HTML5 Canvas, but not able to understand how to rotate the inner circles? Or is there any other 3rd party library to do this more easily.

// CONSTANTS
const LAYER_3 = 3
const MAIN_RADIUS = 250

var context = document.getElementById('testCanvas').getContext('2d')

// draw a circle
context.beginPath();
context.fillStyle = 'orange'
context.arc(MAIN_RADIUS, MAIN_RADIUS, MAIN_RADIUS, 0, 2 * Math.PI, false)
context.fill()
for (i = 0; i < LAYER_3; i++) {
  const PARENT_RADIUS = (MAIN_RADIUS / 2)
  console.log(PARENT_RADIUS)
  context.beginPath();
  context.globalCompositeOperation = 'source-over'
  context.fillStyle = 'blue'
  if (i == 0) {
    context.arc(PARENT_RADIUS, MAIN_RADIUS - (PARENT_RADIUS / 2), PARENT_RADIUS / 2, 0, 2 * Math.PI, false)
  } else if (i == 1) {
    context.arc(PARENT_RADIUS, MAIN_RADIUS - (PARENT_RADIUS / 2), PARENT_RADIUS / 2, 0, 2 * Math.PI, false)
  } else if (i == 2) {
    context.arc(PARENT_RADIUS, MAIN_RADIUS - (PARENT_RADIUS / 2), PARENT_RADIUS / 2, 0, 2 * Math.PI, false)
  }
  context.closePath()
  context.fill()
}
<canvas id="testCanvas" width="500" height="500"></canvas>


Solution

  • In your code you have not used the context.rotate so yes the circles are not going to rotate...
    You might want to read:
    https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/rotate

    Here is an example using your code as a starting point

    const canvas = document.getElementById('testCanvas')
    const context = canvas.getContext('2d')
    const PARENT_RADIUS = 100
    const CHILDREN_RADIUS = 40
    
    // Move to the center of the canvas
    context.translate(canvas.width / 2, canvas.height / 2);
    context.beginPath();
    context.fillStyle = 'orange'
    context.arc(0, 0, PARENT_RADIUS, 0, 2 * Math.PI)
    context.fill()
    
    // Draw the inner circles
    context.fillStyle = 'blue'
    for (i = 0; i < 3; i++) {
      context.beginPath();
      context.rotate(2 * Math.PI / 3);
      context.arc(CHILDREN_RADIUS * 1.3, 0, CHILDREN_RADIUS, 0, 2 * Math.PI)
      context.fill()
    }
    <canvas id="testCanvas" width="200" height="200"></canvas>