【问题标题】:Finding point n% away from the centre of a semicircle in Javascript?在Javascript中找到距半圆中心n%的点?
【发布时间】:2011-10-12 15:59:55
【问题描述】:

很抱歉,数学真的不是我的强项。通常我能过得去,但这让我完全被难住了。

我正在尝试用 HTML/CSS/Javascript 编写一个测验结果屏幕。

在我的界面上,我有一个半圆(目标的右半球)。

我有一系列“分数”(100 分的整数 - 所以 50、80、90 等)。

我需要将这些点绘制在半圆上,使其距离中心 n%,其中 n 是每个分数的值 - 分数越高,点就会出现在离目标中心越近的位置。

我知道我的半圆有多宽,并且已经处理了 % 值的转换,因此较高的值看起来更靠近中心,而较低的值看起来更远。

我无法理解的是,将这些点绘制在一条从目标的中心点 (x = 0, y = 目标高度/2) 以随机角度向外延伸的线上(因此这些点不会'不重叠)。

欢迎提出任何建议!

【问题讨论】:

    标签: javascript math interface


    【解决方案1】:

    你有一个你想要这个样子的例子吗?听起来您想将圆分成N 切片,其中N 是您需要显示的点数,然后沿着每个半径绘制点。所以你可能会有类似的东西:

    编辑:代码围绕原点旋转,而不是指定的圆

    var scores = [];
    //...
    //assume scores is an array of distances from the center of the circle
    var points = [];
    var interval = 2 * Math.PI / N;
    var angle;
    for (var i = 0; i < N; i++) {
        angle = interval * i;
        //assume (cx, cy) are the coordinates of the center of your circle
        points.push({
            x: scores[i] * Math.cos(angle) + cx,
            y: scores[i] * Math.sin(angle) + cy
        });
    }
    

    然后您可以绘制points,但您认为合适。

    【讨论】:

    • 非常感谢!虽然我本身没有使用这种方法,但最终结果几乎相同......见下文。
    【解决方案2】:

    经过多次头疼后,我设法得出了这个解决方案(在一位比我更擅长这种事情的同事的帮助下):

    (arr_result 是一个包含 ID 和分数的数组 - 分数是 100 的百分比)

    for (var i = 0; i < arr_result.length; i++){
    
         var angle = angleArray[i]; // this is an array of angles (randomised) - points around the edge of the semicircle
    
         var radius = 150; // width of the semicircle
    
         var deadZone = 25 // to make matters complicated, the circle has a 'dead zone' in the centre which we want to discount
         var maxScore = 100
         var score = parseInt(arr_result[i]['score'], 10)
    
         var alpha = angle * Math.PI
         var distance = (maxScore-score)/maxScore*(radius-deadZone) + deadZone
         var x = distance * Math.sin(alpha)
         var y = radius + distance * Math.cos(alpha)
    
         $('#marker_' + arr_result[i]['id'], templateCode).css({ // target a specific marker and move it using jQuery
             'left' : pointX,
             'top': pointY
         });
     }
    

    我省略了用于生成角度数组和随机化该数组的代码 - 这仅用于演示目的,因此标记不会重叠。

    在移动标记之前,我还对坐标做了一些奇怪的事情(同样,这已被省略),因为我希望该点位于标记的底部中心而不是左上角。

    【讨论】:

      猜你喜欢
      • 2012-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-05
      • 1970-01-01
      • 2010-12-10
      • 1970-01-01
      • 2017-03-09
      相关资源
      最近更新 更多