如何实时影响滑块?
基本上,我想在顶部有一个滑块,可以实时影响画布(例如圆的半径)中的某些值。
这就是我到目前为止的目标,它确实可以完成我想要的,除了我希望它移动滑块而不是必须按钮时改变。
<input type="range" id="MySldr" value="15" min="1" max="100">
<button class="Btn">Draw</button>
<canvas class="result"></canvas>
<script>
let Btn = document.querySelector(".Btn");
Btn.addEventListener("click", () => {
let res = document.querySelector(".result");
var ctx = res.getContext("2d");
let SldrVal = document.getElementById("MySldr").value;
ctx.clearRect(0, 0, 1000, 1000);
ctx.beginPath();
ctx.arc(125, 125, SldrVal, 0, 2 * Math.PI);
ctx.stroke();
ctx.font = "30px Arial";
ctx.fillText(SldrVal, 10, 50);
});
</script>
我是JS的新手,非常简单,非常简单答案会很好,但是任何事情都值得赞赏。
Basically, I want to have a slider at the top that can affect some value in the canvas, like the radius of a circle, in real-time.
This is what I have so far, it does exactly what I want, except I want it to change as you move the slider instead of having to push the button.
<input type="range" id="MySldr" value="15" min="1" max="100">
<button class="Btn">Draw</button>
<canvas class="result"></canvas>
<script>
let Btn = document.querySelector(".Btn");
Btn.addEventListener("click", () => {
let res = document.querySelector(".result");
var ctx = res.getContext("2d");
let SldrVal = document.getElementById("MySldr").value;
ctx.clearRect(0, 0, 1000, 1000);
ctx.beginPath();
ctx.arc(125, 125, SldrVal, 0, 2 * Math.PI);
ctx.stroke();
ctx.font = "30px Arial";
ctx.fillText(SldrVal, 10, 50);
});
</script>
I'm fairly new to JS and self-taught so simple answers would be nice but anything is appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这不是事件,而是演示了一个称为“游戏循环”的事情。非常适合动画移动的事物。
requestAnimationFrame
就像下一个动画框架的settimeout
(这样它将平滑)。每秒大约60次。This, instead of events, demonstrates a thing call "the game loop". Great for animating things that moves. The
requestAnimationFrame
is like asetTimeout
for the next animation frame (so it'll be smooth). It's about 60 times per second.您可以在
输入
范围元素上收听更改
事件。You can listen for
change
event on theinput
range element.除非您需要/需要您的程序不断重新绘制,否则您不需要
requestAnimationFrame()
。我也看不到每个帧刷新元素的重点。您可以在eventlistener
上使用输入
进行实时输入。Unless you want/need your program to be constantly redrawing you don't need
requestAnimationFrame()
. I also don't see the point in getting the element every frame refresh. You can useinput
on youreventListener
for live inputs.