如何计算HTML Canvas弧的结束角度的x和y坐标?

时间:2017-04-13 15:56:54

标签: javascript html5 canvas

我有一个HTML5画布,我使用下面的代码绘制圆弧:

c = document.querySelector("#myCanvas");
ctx = c.getContext("2d");
var startAngle = 0;
var endAngle = 0.25;
var xPos = 300;
var yPos = 200;
var radius = 100;

ctx.beginPath();
ctx.arc(xPos, yPos, radius, startAngle*Math.PI, endAngle*Math.PI);
ctx.stroke();
ctx.closePath();

如何计算endAngle * Math.PI生成的结束角度的x和y坐标?

1 个答案:

答案 0 :(得分:1)

如果我理解正确,你可以通过以下方式实现这一目标......

var c = document.querySelector("#canvas");
var ctx = c.getContext("2d");
var startAngle = 0; //degree
var endAngle = 229; //degree
var xPos = 100;
var yPos = 100;
var radius = 60;

// compute x and y coordinates of the end angle relative to canvas
var x = xPos + Math.cos(endAngle * Math.PI / 180) * radius;
var y = yPos + Math.sin(endAngle * Math.PI / 180) * radius;

ctx.beginPath();
ctx.arc(xPos, yPos, radius, startAngle * Math.PI / 180, endAngle * Math.PI / 180);
ctx.stroke();

console.log('angle ended in position x:', x|0, ', y:', y|0);
canvas {
  border: 1px solid lightgrey;
}
<canvas id="canvas" width="200" height="200"></canvas>