如何让圆半径随滑块输入而变化?

How do i get the circle radius to change with the slider input?

我正在尝试创建一个滑块,它可以让我通过更改半径来调整圆的大小。我可以设置一次半径,但是当滑块改变时它没有反应。

您可以在此处查看代码:https://codepen.io/ydunga/pen/MWbYoKB

 <canvas id = "canvas1" style = "background-color: yellow" height = "200" iwdth = "500"></canvas>

radius: <input id = "radius" type = "number" min = "0" max = "50" value = "15" oninput = "draw();">

var can1 = document.getElementById("canvas1");
var ctx1 = can1.getContext("2d");

let radius = document.getElementById('radius').value

function draw() {
  ctx1.clearRect(0,0,200,500);
  ctx1.beginPath();
ctx1.arc(50,50, radius, 0, 2*Math.PI);
ctx1.fillStyle = "red";
ctx1.fill();
}

draw()

使用以下内容:

var can1 = document.getElementById("canvas1");
var ctx1 = can1.getContext("2d");

let radius = document.getElementById('radius');

function draw() {
  ctx1.clearRect(0, 0, 200, 500);
  ctx1.beginPath();
  ctx1.arc(50, 50, parseInt(radius.value), 0, 2 * Math.PI);
  ctx1.fillStyle = "red";
  ctx1.fill();
}

draw()
<canvas id="canvas1" style="background-color: yellow" height="200" width="500"></canvas> radius: <input id="radius" type="number" min="0" max="50" value="15" oninput="draw();">

当您将 radius 声明为 document.getElementById('radius').value 时,您检查一次值,但不是经常检查。您应该在每次调用函数时检查函数内部的值(例如,将 radius 声明为一个元素,然后执行 radius.value)。

function draw() {
  / * scope your variables if you can to prevent other code from accidentally changing these! */
  var can1 = document.getElementById("canvas1");
  var ctx1 = can1.getContext("2d");
  let radius = document.getElementById('radius');
  
  if (radius.value > 51 ) { return; } /* good idea to add input validation since the canvas will go crazy if you enter 500. */
  
  ctx1.clearRect(0, 0, 200, 500);
  ctx1.beginPath();
  ctx1.arc(50, 50, parseInt(radius.value), 0, 2 * Math.PI);
  ctx1.fillStyle = "red";
  ctx1.fill();
}

draw()
<canvas id = "canvas1" style = "background-color: yellow" height = "200" width = "500"></canvas>

radius: <input id = "radius" type = "number" min = "0" max = "50" value = "15" oninput="draw()" > 
<!-- Added the oninput, and corrected a spelling mistake on the canvas width was spelled iwdth -->