[英]HTML5 canvas arc code correction
您好,我需要在模拟时钟的时间间隔之间画一条弧线。 我需要一个简单的代码,将开始时间和结束时间作为输入,并以此为基础绘制圆弧。 例如,如果我将11:00作为开始时间,将12:00作为结束时间,那么它应该在11:00到12点之间画一条弧线。 如您所见,在运行此代码时,输出错误,这是指圆弧绘制位置不正确。 它应该在11点到12点之间画一个弧,但不是。 请帮忙。
<!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>
因为角度0从圆的最右边开始。 因此,您只需要移动-pi/2
得到正确的结果。 因此,通过-Math.PI/2
更改startAngle
和endAngle
:
var startAngle = 0 - (Math.PI / 2); // -Math.PI / 2
var endAngle = (2 * Math.PI) - (Math.PI / 2); // 3 * Math.PI / 2
....
请注意,在您的代码中,它不使用这些来计算时钟calculateAngle()
。 因此,您需要在此处从函数的角度减去:
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;
}
这是一个懒惰的小提琴 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.