Search code examples
javascripthtmlhtml5-canvas

How to make slider affect a canvas in real time?


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>

JSFiddle

I'm fairly new to JS and self-taught so simple answers would be nice but anything is appreciated.


Solution

  • This, instead of events, demonstrates a thing call "the game loop". Great for animating things that moves. The requestAnimationFrame is like a setTimeout for the next animation frame (so it'll be smooth). It's about 60 times per second.

    let canvas = document.querySelector(".result");
    var ctx = canvas.getContext("2d");
    
    function drawRect() {
      let SldrVal = document.getElementById("MySldr").value;
      //ctx.strokeStyle = "#305ef2";
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      ctx.beginPath();
      ctx.arc(canvas.width / 2, canvas.height / 2, SldrVal, 0, 2 * Math.PI);
      ctx.stroke();
      ctx.font = "30px Arial";
      ctx.fillText(SldrVal, 10, 50);
    
      requestAnimationFrame(drawRect)
    }
    
    drawRect()
    <input type="range" id="MySldr" value="15" min="1" max="100">
    <br>
    <canvas class="result" width="400" height="200"></canvas>