javascript - 如何让圆半径随滑块输入而变化?
问题描述
我正在尝试创建一个滑块,让我通过更改半径来调整圆的大小。我可以设置一次半径,但是当滑块改变时它没有响应。
您可以在此处查看代码: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()
解决方案
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 -->
推荐阅读
- javascript - 一旦您的元素不再连接,如何处理“connectedCallback 可能会被调用”编码一个 Web 组件
- r - 错误:尝试使用 read.csv() 读取 csv 文件时出现“意外输入..”
- php - 使用数据库中的图像路径在 php 中显示图像
- python - TableView 小部件仅在排序后填充数据
- c++ - 如何比较c ++列表中的两个连续元素
- r - 如何编辑由使用绘图创建它的其他函数生成的 R 图?
- c# - XML 子节点读取
- python - 在 python 中使用 selenium/chromedriver 发布 Instagram 故事
- angular - fxFlex 不调整元素大小
- ionic-framework - 离子 + 电容器的 SSL 固定问题