Canvas How to - Draw red circle along triangle








Question

We would like to know how to draw red circle along triangle.

Answer


<!--  w w  w  .  j a v  a 2  s .  c o  m-->
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){
    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 < 5; 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;

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

}//]]>  
</script>
</head>
<body>
  <canvas id="canvas" width="300" height="300" />
</body>
</html>

The code above is rendered as follows: