How do I calculate a point on a circle’s circumference?

后端 未结 4 1382
悲&欢浪女
悲&欢浪女 2020-11-22 15:02

How can the following function be implemented in various languages?

Calculate the (x,y) point on the circumference of a circle, given input values of:

4条回答
  •  长情又很酷
    2020-11-22 15:20

    Implemented in JavaScript (ES6):

    /**
        * Calculate x and y in circle's circumference
        * @param {Object} input - The input parameters
        * @param {number} input.radius - The circle's radius
        * @param {number} input.angle - The angle in degrees
        * @param {number} input.cx - The circle's origin x
        * @param {number} input.cy - The circle's origin y
        * @returns {Array[number,number]} The calculated x and y
    */
    function pointsOnCircle({ radius, angle, cx, cy }){
    
        angle = angle * ( Math.PI / 180 ); // Convert from Degrees to Radians
        const x = cx + radius * Math.sin(angle);
        const y = cy + radius * Math.cos(angle);
        return [ x, y ];
    
    }
    

    Usage:

    const [ x, y ] = pointsOnCircle({ radius: 100, angle: 180, cx: 150, cy: 150 });
    console.log( x, y );
    

    Codepen

    /**
     * Calculate x and y in circle's circumference
     * @param {Object} input - The input parameters
     * @param {number} input.radius - The circle's radius
     * @param {number} input.angle - The angle in degrees
     * @param {number} input.cx - The circle's origin x
     * @param {number} input.cy - The circle's origin y
     * @returns {Array[number,number]} The calculated x and y
     */
    function pointsOnCircle({ radius, angle, cx, cy }){
      angle = angle * ( Math.PI / 180 ); // Convert from Degrees to Radians
      const x = cx + radius * Math.sin(angle);
      const y = cy + radius * Math.cos(angle);
      return [ x, y ];
    }
    
    const canvas = document.querySelector("canvas");
    const ctx = canvas.getContext("2d");
    
    function draw( x, y ){
    
      ctx.clearRect( 0, 0, canvas.width, canvas.height );
      ctx.beginPath();
      ctx.strokeStyle = "orange";
      ctx.arc( 100, 100, 80, 0, 2 * Math.PI);
      ctx.lineWidth = 3;
      ctx.stroke();
      ctx.closePath();
    
      ctx.beginPath();
      ctx.fillStyle = "indigo";
      ctx.arc( x, y, 6, 0, 2 * Math.PI);
      ctx.fill();
      ctx.closePath();
      
    }
    
    let angle = 0;  // In degrees
    setInterval(function(){
    
      const [ x, y ] = pointsOnCircle({ radius: 80, angle: angle++, cx: 100, cy: 100 });
      console.log( x, y );
      draw( x, y );
      document.querySelector("#degrees").innerHTML = angle + "°";
      document.querySelector("#points").textContent = x.toFixed() + "," + y.toFixed();
    
    }, 100 );

    Degrees: 0

    Points on Circle (x,y): 0,0

提交回复
热议问题