Hello all I need to draw an arc between a time interval in analog clock. I need a simple code that takes start time and end time as input and draw arc based on that. For example if I put 11:00 as start time and 12:00 as end time then it should draw an arc starting from 11:00 o'clock to 12 o'clock. As you can see when you run this code the output is wrong I mean the arc drawn position is not correct. It should draw an arc starting from 11 o'clock to 12 o'clock but its not. Please help.
<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="578" height="250"></canvas>
<script>
function calculateAngle(hours,mins) {
var hDegrees = (hours * 30) + (mins * 0.5);
var angle = (hDegrees * Math.PI/180); //convert in radians
console.log(hDegrees);
console.log(angle);
return angle;
}
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var x = canvas.width / 2;
var y = canvas.height / 2;
var radius = 100;
var startAngle = 0;
var endAngle = 2 * Math.PI;
var counterClockwise = false;
context.beginPath();
context.arc(x, y, radius, startAngle, endAngle, counterClockwise);
context.lineWidth = 10;
// line color
context.fillStyle = '#481e63';
context.fill();
context.strokeStyle = '#62278d';
context.stroke();
context.beginPath();
context.arc(x, y, radius, calculateAngle(11,0), calculateAngle(12,0), counterClockwise);
context.strokeStyle = '#DD2B8F';
context.stroke();
</script>
</body>
</html>
Because the angle 0 starts on the very right of the circle. So you just need to shift by -pi/2
and you will have the correct result. So change the startAngle
and endAngle
by -Math.PI/2
:
var startAngle = 0 - (Math.PI / 2); // -Math.PI / 2
var endAngle = (2 * Math.PI) - (Math.PI / 2); // 3 * Math.PI / 2
....
Note that in your code to calculate the clock calculateAngle()
, you don't use these. So you will need to subtract from the angle in your function here:
function calculateAngle(hours,mins) {
var hDegrees = (hours * 30) + (mins * 0.5);
var angle = (hDegrees * Math.PI/180); //convert in radians
angle -= Math.PI/2 // <-- Here
console.log(hDegrees);
console.log(angle);
return angle;
}
And here is a lazily made fiddle .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.