I am trying to create a web page with the following layout using React:
The elements should fill the page width and height exactly and respond to change of the browser window size.
I can achieve this behavior using a flexbox, but the canvas content is extremely blurry.
This can be solved by setting the canvas resolution to it's dimensions inside an useEffect
callback like this:
canvas.width = canvas.offsetWidth;
canvas.height = canvas.offsetHeight;
However, this stops the canvas from responding to the resizing of the page - more specifically, the canvas aspect ratio does not follow the page dimensions when the page size increases and it does not change at all when the page size decreases.
I created two examples to illustrate the issue:
Do you have any suggestions how to reconcile this behavior? I have seen similar questions asked here but none of the examples actually worked.
Did you try to setting the canvas
height and width before getting the context
:
useEffect(() => {
let canvas = canvasRef.current;
canvas.width = canvas.offsetWidth;
canvas.height = canvas.offsetHeight;
const context = canvas.getContext("2d");
window.requestAnimationFrame(() => {
draw(context, canvas);
});
}, [timer]);
I recommend you to use window.requestAnimationFrame since you are re-redering the component multiples times to perform an animation
Working example: https://codesandbox.io/s/react-playground-forked-upojf8?file=/plot.js:806-1079
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.