用给定半径计算圆周

时间:2017-11-12 23:25:49

标签: javascript geometry

我试图通过从绘制圆的给定代码中检索已定义的半径来计算和显示周长。这是我输入公式错误的方式还是需要在同一个脚本部分?

function draw() {
  var canvas = document.getElementById('circle');
  if (canvas.getContext) {
    var ctx = canvas.getContext('2d');
    var X = canvas.width / 2;
    var Y = canvas.height / 2;
    var R = 45;
    ctx.beginPath();
    ctx.arc(X, Y, R, 0, 2 * Math.PI, false);
    ctx.lineWidth = 3;
    ctx.strokeStyle = '#FF0000';
    ctx.stroke();
  }
}

function calculatecircumference() {
  var circumference = ((2) * (Math.Pi) * (R));
}

document.getElementById("Circumference").innerHTML = circumference;
<!Doctype>
<html>

<body onload="draw();">
  <canvas id="circle" width="150" height="150"></canvas>
</body>

<p>Circumference: <span id="Circumference"></span></p>

</html>

2 个答案:

答案 0 :(得分:0)

实际上数学PI是错误的......你写了 Math.Pi

var circumference = ((2) * (Math.Pi) * (R));

但实际上它是 Math.PI

var circumference = ((2) * (Math.PI) * (R));

因此它返回半径为45的 NaN

检查以下代码....还需要调用calculatecircumference函数..并将Radius作为参数传递

function draw() {
  var canvas = document.getElementById('circle');
  if (canvas.getContext) {
    var ctx = canvas.getContext('2d');
    var X = canvas.width / 2;
    var Y = canvas.height / 2;
    var R = 45;
    ctx.beginPath();
    ctx.arc(X, Y, R, 0, 2 * Math.PI, false);
    ctx.lineWidth = 3;
    ctx.strokeStyle = '#FF0000';
    ctx.stroke();
	calculatecircumference(R);
  }
}

function calculatecircumference(R) {
  var circumference = ((2) * (Math.PI) * (R));
    
document.getElementById("Circumference").innerHTML = circumference;

}
<body onload="draw();">
  <canvas id="circle" width="150" height="150"></canvas>
</body>

<p>Circumference: <span id="Circumference"></span></p>

答案 1 :(得分:0)

你有三个问题:

  • 首先,您需要授予calculatecircumference()范围以访问R。这可以通过从calculatecircumference()内调用draw()并将其作为函数参数传递来完成。您还需要告诉calculatecircumference()将其函数参数分配给局部变量R,方法是将其写为calculatecircumference(R)
  • 其次,document.getElementById("Circumference").innerHTML无法访问circumference的范围。只需在document.getElementById("Circumference").innerHTML = circumference。{/ li>中运行caluclatecircumference()
  • 最后,您在Math.Pi中致电Math.PI而非calculatecircumference()PI 必须为大写。

纠正这三个问题可以解决问题,如下所示:

&#13;
&#13;
function draw() {
  var canvas = document.getElementById('circle');
  if (canvas.getContext) {
    var ctx = canvas.getContext('2d');
    var X = canvas.width / 2;
    var Y = canvas.height / 2;
    var R = 45;
    ctx.beginPath();
    ctx.arc(X, Y, R, 0, 2 * Math.PI, false);
    ctx.lineWidth = 3;
    ctx.strokeStyle = '#FF0000';
    ctx.stroke();
    calculatecircumference(R);
  }
}

function calculatecircumference(R) {
  var circumference = ((2) * (Math.PI) * (R));
  document.getElementById("Circumference").innerHTML = circumference;
}
&#13;
<!Doctype>
<html>

<body onload="draw();">
  <canvas id="circle" width="150" height="150"></canvas>
</body>

<p>Circumference: <span id="Circumference"></span></p>

</html>
&#13;
&#13;
&#13;

希望这有帮助! :)