sidarcy
sidarcy

Reputation: 3008

Programmatically draw this pattern with HTML5 Canvas

How would I programmatically draw the pattern below using HTML5 canvas?

I have the logic to draw the circles here. Additionally I can draw Arcs see thisbin however I'm struggling with the maths required to bring it all together into the below pattern.

It is 7 arcs, each contains a different amount of circles (outer to inner: 33, 29, 26, 23, 21, 18, 15)

Im not to familiar with Canvas but think it could be the solution for my problem.

Desired Pattern

Upvotes: 0

Views: 1503

Answers (1)

Cyril Cherian
Cyril Cherian

Reputation: 32327

You can do somethig like this:

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var radius = 200;//outer radius
var rows = 7;//number of rows
var diff = 20;//distance between each row
var circle_count = [33, 29, 26, 23, 21, 18, 15];
for (var j = 0; j < rows; j++) {
  //the circle count to be made
  var count = circle_count.shift();

  var current_radius = radius - j*diff;
  for (var i = 0; i < count; i++) {
    //devide 180 degrees by the number of circle to draw 
    var angle = Math.PI / (count-1) * i*-1;
    //x coordinate
        var x = current_radius * Math.cos(angle) + 300;
    //y coordinate
    var y = current_radius * Math.sin(angle) + 100;
    ctx.beginPath();
    ctx.arc(x, y, 5, 0, 2 * Math.PI);
    ctx.stroke();
  }
}

working fiddle here

hope this helps!

Upvotes: 4

Related Questions