首页 > 解决方案 > 如何让圆半径随滑块输入而变化?

问题描述

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

您可以在此处查看代码: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()

标签: javascripthtmlhtml5-canvas

解决方案


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


推荐阅读