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

Viewed 337

I am trying to create a slider which lets me resize the circle, by changing the radius. I can set the radius once, but it doesn't respond when the slider changes.

You can review the code here: 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()
2 Answers

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 -->

Use the following:

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();">

When you declare radius as document.getElementById('radius').value, you check the value ONCE, but not constantly. You should be checking the value inside the function everytime it is called (e.g, declare radius as an element, then do radius.value).

Related