admin管理员组

文章数量:1417097

Evidentially my trig is a bit rusty. How can I get the minutes to wrap around the clock?

codepen [update: forgot codepen isn't versioned like jsfiddle; this 'pen' is a work in progress and no longer represents the problem I had at the time of this question]

Javascript:

var r = $('.face').width()/2;
var j = r-18;
for(var min=0; min<60; min += 5) {
  var str = min < 10 ? '0'+min : String(min);
  var x = j*Math.sin(Math.PI*2*(min/60));
  var y = j*Math.cos(Math.PI*2*(min/60));
  console.log(x);
  $('<div>',{'class':'time'})
    .text(str)
    .css({
      marginLeft: (x+r-12)+'px',
      marginTop: (-y+r-12)+'px'
    })
    .appendTo('.face');
}

Evidentially my trig is a bit rusty. How can I get the minutes to wrap around the clock?

codepen [update: forgot codepen isn't versioned like jsfiddle; this 'pen' is a work in progress and no longer represents the problem I had at the time of this question]

Javascript:

var r = $('.face').width()/2;
var j = r-18;
for(var min=0; min<60; min += 5) {
  var str = min < 10 ? '0'+min : String(min);
  var x = j*Math.sin(Math.PI*2*(min/60));
  var y = j*Math.cos(Math.PI*2*(min/60));
  console.log(x);
  $('<div>',{'class':'time'})
    .text(str)
    .css({
      marginLeft: (x+r-12)+'px',
      marginTop: (-y+r-12)+'px'
    })
    .appendTo('.face');
}
Share Improve this question edited Sep 30, 2013 at 21:22 mpen asked Sep 30, 2013 at 19:35 mpenmpen 284k281 gold badges892 silver badges1.3k bronze badges 2
  • 1 Turns out your trig is fine. – Reinstate Monica -- notmaynard Commented Sep 30, 2013 at 19:50
  • Incidentally, you can simplify Math.PI*2*(min/60) to Math.PI*min/30, or even just min*0.10472 – Blazemonger Commented Sep 30, 2013 at 19:56
Add a ment  | 

3 Answers 3

Reset to default 8

All your .time divs are below one another. Give the .time class absolute positioning.

Assuming min is between 0-60, and bearing in mind that there are 360 degrees in a circle:

var degToMin = 360/60; // 6
var minDeg = min * degToMin; // this will tell us how many degrees around the circle the minutes are
var minRad = minDeg * (Math.PI/180); // convert to radians
var x = j*Math.cos(minRad); // cos is the x coord, while sin is the y coord
var y = j*Math.sin(minRad);

Going from 0 to 360 degrees (0 to 2 pi radians) normally starts at 3 o'clock, and goes counterclockwise.

So we need to reverse the direction so that it goes clockwise, and rotate it counterclockwise 90 degrees (pi/2 radians) so that it starts at 12 o'clock.

Each hour runs through pi/6 radians, so the position at hour h would be:

x = x_c + r cos (-h*pi/6 + pi/2)
y = y_c + r sin (-h*pi/6 + pi/2)

where the center of your clock is (x_c, y_c) and the radius of your clock is r.

本文标签: javascriptHow to position these numbers around a clockStack Overflow