user4227915
user4227915

Reputation:

Draw indicators in five minutes interval in a clock

I'm learning canvas, and I'm trying to draw a clock..

By now, I have this:

var canvas = document.createElement("canvas");
canvas.width = 100;
canvas.height = 100;
document.body.appendChild(canvas);

if (!canvas.getContext) {
    console.log("Good morning! .. Please check your canvas");
}
else {
    var ctx = canvas.getContext("2d");

    var path = new Path2D();

    // outer border
    path.moveTo(100,50);
    path.arc(50,50,50,0,Math.PI*2,true);

    // inner border
    path.moveTo(97,50);
    path.arc(50,50,47,0,Math.PI*2,true);

    // indicators: fifteen in fifteen minutes
    path.lineTo(90,50);
    path.moveTo(3,50);
    path.lineTo(10,50);
    path.moveTo(50,3);
    path.lineTo(50,10);
    path.moveTo(50,97);
    path.lineTo(50,90);

    // show canvas
    ctx.stroke(path);
}

As you can see, I drawed the indicators one by one (in fifteen minutes interval).

I'd like to draw it in interval of five minutes ..

Is there any genial for-loop/mathematic to do this?

Thanks for your time.


Edit: just to share the result.

Upvotes: 0

Views: 60

Answers (1)

Domi
Domi

Reputation: 26

you need some trigonometrics and a for-loop for this.

You might know that a circle is defined as all points like P(cos(x),sin(x)). In this case the x value in the sin and cos functions has to be calculated as follows:

x=50+50*Math.cos((i/numticks)*2*Math.PI)

So what does all this mean?

  • The first 50 moves the circle to the center of the canvas.
  • (i/numticks) scales the number of ticks to a range from 0 to 1

then we multiply all this by 2*Pi and that gives the argument for the sin and cos.

var numticks=12
for(var i = 0;i <= numticks;i++) {
   path.moveTo(50+50*Math.cos((i/numticks)*2*Math.PI),50+50*Math.sin((i/numticks)*2*Math.PI));
   path.lineTo(50+45*Math.cos((i/numticks)*2*Math.PI),50+45*Math.sin((i/numticks)*2*Math.PI));
}  

Upvotes: 1

Related Questions