繁体   English   中英

圆坐标到Javascript中的数组

[英]Circle coordinates to array in Javascript

在JavaScript中将圆的坐标添加到数组的最佳方法是什么? 到目前为止,我只能做半圈,但我需要一个公式,将整个圆圈返回到两个不同的数组: xValuesyValues (我正在尝试获取坐标,以便我可以沿路径设置对象的动画。)

这是我到目前为止所拥有的:

circle: function(radius, steps, centerX, centerY){
    var xValues = [centerX];
    var yValues = [centerY];
    for (var i = 1; i < steps; i++) {
        xValues[i] = (centerX + radius * Math.cos(Math.PI * i / steps-Math.PI/2));
        yValues[i] = (centerY + radius * Math.sin(Math.PI * i / steps-Math.PI/2));
   }
}

你的循环应该像这样设置:

for (var i = 0; i < steps; i++) {
    xValues[i] = (centerX + radius * Math.cos(2 * Math.PI * i / steps));
    yValues[i] = (centerY + radius * Math.sin(2 * Math.PI * i / steps));
}
  • 从0开始循环
  • 逐步完成整个2 * PI范围,而不仅仅是PI。
  • 你不应该有var xValues = [centerX]; var yValues = [centerY]; var xValues = [centerX]; var yValues = [centerY]; - 圆圈的中心不是它的一部分。

Bresenham的算法更快。 你听说它与绘制直线有关,但是有一种圆形算法的形式。

无论你是使用它还是继续进行三角计算(这些天都非常快) - 你只需要绘制圆的1/8。 通过交换x,y你可以得到另一个1/8,然后是x,y和两者的负数 - 交换和未交换 - 为你提供所有其余圆圈的分数。 加速8倍!

更改:

Math.PI * i / steps

至:

2*Math.PI * i / steps

一个完整的圆是2pi弧度,你只需要pi弧度。

如果你已经有半个圆圈,只需镜像点数即可获得另一半
确保按正确的顺序执行此操作。

更具体地说,对于另一半,你只需用“ - sin(...) ”替换“ + sin(...) - sin(...)

你需要使用部分函数将弧度输入cos和sin; 因此,取圆圈的四分之一或一半所得的值,并将它们反映在中心点的轴上以获得整圆。

那说JavaScript的罪恶和cos并不那么挑剔,所以你必须将你的弧度减半或者其他东西; 我把它写成:

function circle(radius, steps, centerX, centerY){
    var xValues = [centerX];
    var yValues = [centerY];
    var table="<tr><th>Step</th><th>X</th><th>Y</th></tr>";
    var ctx = document.getElementById("canvas").getContext("2d");
    ctx.fillStyle = "red"
    ctx.beginPath();
    for (var i = 0; i <= steps; i++) {
        var radian = (2*Math.PI) * (i/steps);
        xValues[i+1] = centerX + radius * Math.cos(radian);
        yValues[i+1] = centerY + radius * Math.sin(radian);
        if(0==i){ctx.moveTo(xValues[i+1],yValues[i+1]);}else{ctx.lineTo(xValues[i+1],yValues[i+1]);}
        table += "<tr><td>" + i + "</td><td>" + xValues[i+1] + "</td><td>" + yValues[i+1] + "</td></tr>";
    }
    ctx.fill();
    return table;
}
document.body.innerHTML="<canvas id=\"canvas\" width=\"300\" height=\"300\"></canvas><table id=\"table\"/>";
document.getElementById("table").innerHTML+=circle(150,15,150,150);

我认为无论出于何种原因你想要xValues [0]和yValues [0]为centerX和centerY。 我无法弄清楚你为什么要这样,因为它们已经传递给函数的值。

通过将步数乘以2,我能够自己解决它:

circle: function(radius, steps, centerX, centerY){
    var xValues = [centerX];
    var yValues = [centerY];
    for (var i = 1; i < steps; i++) {
        xValues[i] = (centerX + radius * Math.cos(Math.PI * i / steps*2-Math.PI/2));
        yValues[i] = (centerY + radius * Math.sin(Math.PI * i / steps*2-Math.PI/2));
   }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM