Draw a line from x,y with a given angle and length

Draw a line from x,y with a given angle and length. DEMO Fiddle

function drawLine(x1,y1,r,theta){
    ctx.clearRect(0, 0, c.width, c.height);    
    ctx.beginPath();
    ctx.moveTo(x1, y1);
    ctx.lineTo(x1 + r * Math.cos(Math.PI * theta / 180.0), y1 + r * Math.sin(Math.PI * theta / 180.0));   
    ctx.closePath();
    ctx.stroke();
  }
Advertisements

Placing Items on a Circle

It can be quite challenging to place items on a circle, But with some help from maths we can 🙂 … DEMO

var radius = 200;
var fields = $('.field'), container = $('#container'),
    width = container.width(), height = container.height(),
    angle = 0, step = (2*Math.PI) / fields.length;
fields.each(function() {
    var x = Math.round(width / 2 + radius * Math.cos(angle) - $(this).width() / 2);
    var y = Math.round(height / 2 + radius * Math.sin(angle) - $(this).height() / 2);
    if (window.console) {
        console.log($(this).text(), x, y);
    }
    $(this).css({
        left: x + 'px',
        top: y + 'px'
    });
    angle += step;
});