Ad

Circle Is Not Connecting Through Lines Properly Using Canvas

- 1 answer

I am trying to create 11 circles which connected through lines with a middle circle. I am trying to draw the circles. Here I have doing some r&d but I could not able to make lines. Please help me to complete this.

 var canvas, ctx;
        var circlePoints = [];
        function createCanvasPainting() {
            
            canvas = document.getElementById('myCanvas');
            if (!canvas || !canvas.getContext) {
                return false;
            }
            canvas.width = 600;
            canvas.height = 600;
            ctx = canvas.getContext('2d');           
            ctx.strokeStyle = '#B8D9FE';
            ctx.fillStyle = '#B8D9FE';
            ctx.translate(300, 250);
            ctx.arc(0, 0, 50, 0, Math.PI * 2); //center circle
            ctx.stroke();
            ctx.fill();
            var angleRotate = 0;
            for (var i=0; i<11; i++) {
                if (i > 0) {
                    angleRotate += 32.72;
                }
                lineToAngle(ctx, 0, 0, 200, angleRotate);
            }
        }

        function lineToAngle(ctx, x1, y1, length, angle) {

            angle *= Math.PI / 180;

            var x2 = x1 + length * Math.cos(angle),
            y2 = y1 + length * Math.sin(angle);
            ctx.beginPath();
            ctx.moveTo(x1, y1);
            ctx.lineTo(x2, y2);
            ctx.lineWidth = 1;
            ctx.arc(x2, y2, 40, 0, Math.PI * 2);
            ctx.fill();
            ctx.stroke();

            circlePoints.push({x: x2, y: y2});
            // console.log(circlePoints);
        }

        createCanvasPainting();
<canvas id="myCanvas"></canvas>

Here is my JSFiddle Link

Ad

Answer

See below I removed all the "noise" from your code.
Just circles with lines connecting with a middle circle.

canvas = document.getElementById('myCanvas');
canvas.width = canvas.height = 200;
ctx = canvas.getContext('2d');
ctx.lineWidth = 1;
ctx.translate(99, 99);
angle = 0;

function draw() {
  ctx.clearRect(-99, -99, 200, 200);
  ctx.beginPath();
  ctx.arc(0, 0, 35 + Math.cos(angle / 3000), 0, Math.PI * 2);
  ctx.stroke();
  ctx.fill();

  for (var i = 0; i < 11; i++) {
    a = angle * Math.PI / 180;
    x = 80 * Math.cos(a)
    y = 80 * Math.sin(a)
    ctx.beginPath();
    ctx.arc(x, y, 18, 0, Math.PI * 2);
    ctx.moveTo(x, y);
    ctx.lineTo(0, 0);
    ctx.fill();
    ctx.stroke();
    angle += 32.7;
  }
}

setInterval(draw, 10);
<canvas id="myCanvas"></canvas>

Ad
source: stackoverflow.com
Ad