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;
}
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;
try to add css in canvas tag
canvas{
width:100%;
max-width:100%;
height:100%;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With