Home > OS >  How to make slider affect a canvas in real time?
How to make slider affect a canvas in real time?

Time:07-07

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 >Draw</button>

<canvas ></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.

CodePudding user response:

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  width="400" height="200"></canvas>

CodePudding user response:

You can listen for change event on the input range element.

document.getElementById("MySldr").addEventListener('change', (event) => {
    let value = event.target.value; // value of the range slider
    // your code here
})

CodePudding user response:

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 use input on your eventListener for live inputs.

let mySldr = document.getElementById("MySldr");
let res = document.querySelector(".result");
let ctx = res.getContext("2d");

mySldr.addEventListener("input", () => {
  mySldr = document.getElementById("MySldr").value;
  ctx.clearRect(0, 0, 1000, 1000);
  ctx.beginPath();
  ctx.arc(125, 125, mySldr, 0, 2 * Math.PI);
  ctx.stroke();
  ctx.font = "30px Arial";
  ctx.fillText(mySldr, 10, 50);
});
<input type="range" id="MySldr" value="15" min="1" max="100">
<canvas ></canvas>

  • Related