以编程方式使用HTML5 Canvas绘制此模式

时间:2016-01-22 08:12:45

标签: javascript html5 canvas html5-canvas drawing

如何使用HTML5 canvas以编程方式绘制下面的模式?

我有绘制圆here的逻辑。另外我可以画弧线看到这个bin然而我正在努力将所有数据整合到下面的模式中。

它是7个弧,每个包含不同数量的圆(从外部到内部:33,29,26,23,21,18,15)

我不熟悉Canvas,但认为它可以解决我的问题。

Desired Pattern

1 个答案:

答案 0 :(得分:2)

你可以这样做:

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();
  }
}

工作小提琴here

希望这有帮助!