以三角形动态排列元素?

时间:2012-02-09 13:30:36

标签: javascript jquery dynamic geometry

我正在寻找一个JS函数来动态排列三角形中的元素,如下图所示:

元素的数量取决于用户的选择,因此每次都会有所不同。 我设法做了一个圆圈,但对于一个三角形来说似乎相当棘手。

3 个答案:

答案 0 :(得分:2)

试试这个:

function drawTriangle(ctx, sideLength) {
  var i = 0, direction = 1;

  ctx.save();
  ctx.strokeStyle = 'rgba(0, 0, 0, 1)';

  ctx.beginPath();

  ctx.moveTo(0, 0);
  for (; i < 3; i += 1) {
    ctx.rotate(Math.PI / -3);
    ctx.lineTo(direction * sideLength, 0);
    ctx.translate(direction * sideLength, 0);
    direction *= -1;
  }

  ctx.closePath();
  ctx.stroke();

  ctx.restore();
}

function drawCircle(ctx) {
  ctx.save();
  ctx.fillStyle = 'rgba(255, 0, 0, 1)';

  ctx.beginPath();
  ctx.arc(0, 0, 3, 0, 2 * Math.PI, true); 
  ctx.closePath();
  ctx.fill();

  ctx.restore();
}

function drawCircles(ctx, num, sideLength) {
  var stepLength = (sideLength * 3) / num, i = 0;

  ctx.save();
  for (; i < num; i += 1) {
    if ((stepLength * i) % sideLength === 0) {
      ctx.rotate(2 * Math.PI / 3);
    }

    drawCircle(ctx);
    ctx.translate(-stepLength, 0);
  }

  ctx.restore();
}

var
  canvas = document.getElementById('canvas'),
  ctx = canvas.getContext('2d'),
  sideLength = 200;

if (ctx) {
  ctx.translate(50, 225);
  drawTriangle(ctx, sideLength);
  drawCircles(ctx, 14 * 3, sideLength);
}

演示:http://jsfiddle.net/ej2Kq/

答案 1 :(得分:1)

在图片上可以清楚地看到,只能以这种方式排列一定数量的元素。该数字应该可被3整除。首先 - 检查该前提条件。然后将三个组中的元素总量分开,并将每个组均匀分布在每个边框上。

答案 2 :(得分:0)

所以现在我想出了这个:

http://jsfiddle.net/ZBVFL/

它完成了这项工作,但我不喜欢手动添加最后一个圆圈。

相关问题