htmlmathcanvasgeometry2d-context-api

How to divide a circle into three equal parts with HTML5 canvas?


enter image description here

How can I divide a circle into three equal parts with HTML5 canvas 2D context API like above figure?

I was trying this

Can somebody suggest a better way? probably with percentages (or in degrees) instead of hard-coded coordinates?

var can = document.getElementById('mycanvas');
var ctx = can.getContext('2d');

ctx.fillStyle = "#BD1981";
ctx.beginPath();
ctx.arc(200, 200, 150, 0, Math.PI*2, true);
ctx.closePath();
ctx.fill();

ctx.strokeStyle = "#FFC8B2";
ctx.lineWidth = "2";
ctx.beginPath();
ctx.moveTo(200, 200);
ctx.lineTo(100, 100);
ctx.closePath();
ctx.stroke();

ctx.beginPath();
ctx.moveTo(200, 200);
ctx.lineTo(350, 200);
ctx.closePath();
ctx.stroke();

ctx.beginPath();
ctx.moveTo(200, 200);
ctx.lineTo(100, 300);
ctx.closePath();
ctx.stroke();

Solution

  • Here is a function (demo) that allows you to specify a starting point, the length and the angle in degrees:

    var drawAngledLine = function(x, y, length, angle) {
        var radians = angle / 180 * Math.PI;
        var endX = x + length * Math.cos(radians);
        var endY = y - length * Math.sin(radians);
    
        ctx.beginPath();
        ctx.moveTo(x, y)
        ctx.lineTo(endX, endY);
        ctx.closePath();
        ctx.stroke();
    }