Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resize canvas according to the parent div element (react)?

I am trying to resize the canvas which is inside a div container. Currently, the div container is big and the canvas is the blue box in it, I want the canvas to occupy the entire gray box.Canvas img

This is my Canvas function

function Canvas() {
  const canvasRef = useRef(null);
  const contextRef = useRef(null);
  const [isDrawing, setIsDrawing] = useState(false);

  useEffect(() => {
    const canvas = canvasRef.current;
    const context = canvas.getContext("2d");
    context.scale(1, 1);
    context.lineCap = "round";
    context.strokeStyle = "white";
    context.linewidth = 5;
    contextRef.current = context;
  }, []);
  const startDrawing = ({ nativeEvent }) => {
    const { offsetX, offsetY } = nativeEvent;
    contextRef.current.beginPath();
    contextRef.current.moveTo(offsetX, offsetY);
    setIsDrawing(true);
  };

  const finishDrawing = () => {
    contextRef.current.closePath();
    setIsDrawing(false);
  };

  const draw = ({ nativeEvent }) => {
    if (isDrawing) {
      const { offsetX, offsetY } = nativeEvent;
      contextRef.current.lineTo(offsetX, offsetY);
      contextRef.current.stroke();
    } else {
      return;
    }
  };
  return (
    <div className="canvas">
      <div className="canvas__header">
        <h1 className="word">Random Word</h1>
      </div>
      <div className="canvas__body">
        <canvas
          onMouseDown={startDrawing}
          onMouseUp={finishDrawing}
          onMouseMove={draw}
          ref={canvasRef}
        ></canvas>
      </div>
    </div>
  );
}

This is my .css file for the canvas, if I set the Width and height to 100% the canvas becomes blurry and overflows out of the div container box.

.canvas {
  flex: 0.6;
  display: flex;`enter code here`
  flex-direction: column;
}

.canvas__header {
  padding: 20px;
  background-color: #1b1b1b;
  display: flex;
  align-items: center;
  justify-content: center;
  border-bottom: 1px solid rgba(126, 255, 158, 0.1);
  max-height: 5vh !important;
  min-height: 5vh !important;
}

.canvas__header > .word {
  color: #7eff9e;
  font-size: 20px;
}

.canvas__body {
  background-color: #242124;
  flex: 1;
}

.canvas__body > canvas {
  background-color: blue;
}
like image 850
DDank Avatar asked Oct 23 '25 14:10

DDank


2 Answers

I was able to fix this by adding these 4 lines of code in the useEffect function:

canvas.style.width = "100%";
canvas.style.height = "100%";
canvas.width = canvas.offsetWidth;
canvas.height = canvas.offsetHeight;
like image 141
DDank Avatar answered Oct 26 '25 03:10

DDank


try to add css in canvas tag

canvas{
   width:100%;
   max-width:100%;
   height:100%;
}
like image 36
Daddys Code Avatar answered Oct 26 '25 05:10

Daddys Code



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!