Search code examples
javascripttypescriptcanvasrectangles

Use 2 Slider inputs to generate a Rectangle (Canvas). On new Inputs, delete the Rectangle


I have 2 slider in my HTML that get me the desired Width and Height of the Rectangle they wanna do in my Canvas. It's working fine but i can't figure out how to delete the one Rectangle that i got before. I tried it with a boolean Value, but it gets messed up because both sliders are in the same Function, so when i move one of those sliders i cant move the other.

Here is my Function to draw the Rectangle:

function drawBackgroundBig(): void {
    if (canvasSet == false) {
        let newHeight: number = parseInt(heightSlider.value);
        // console.log(heightSlider.value);
        
        let newWidth: number = parseInt(widthSlider.value);
        // console.log(widthSlider.value);

        crc2.fillStyle = "red";
        crc2.fillRect(0, 0, newWidth, newHeight);
        crc2.stroke();
        crc2.save();
        newHeight = height;
        newWidth = width;
    }
    else {
        crc2.clearRect(0, 0, width, height);
        crc2.save();
    }
}

Solution

  • I would just recommand you to invert the content of if and else. Put crc2.clearRect(0, 0, width, height); crc2.save(); at the beginning of your function and you should get what you're looking for.

    let ctx=can.getContext("2d");
    let prevWidth=0;
    let prevHeight = 0;
    
    let drawBackgroundBig = () => {
    
        ctx.clearRect(0, 0, prevWidth, prevHeight);
      ctx.save();
            
      let newHeight = parseInt(myRange1.value);
      // console.log(heightSlider.value);
    
      let newWidth = parseInt(myRange2.value);
      // console.log(widthSlider.value);
    
      ctx.fillStyle = "red";
      ctx.fillRect(0, 0, newWidth, newHeight);
      ctx.stroke();
      ctx.save();
      
      prevWidth = newWidth;
      prevHeight = newHeight;
      
    }
    myRange1.onchange=()=>{drawBackgroundBig();}
    myRange2.onchange=()=>{drawBackgroundBig();}
    <canvas id="can" height=300 width=300 ></canvas>
    <div>
      <input type="range" min="1" max="100" value="50" id="myRange1">
      <input type="range" min="1" max="100" value="50" id="myRange2">
    </div>