Adjusting the size of a canvas element based on changes in the browser window dimensions

I'm currently working on developing a website layout in React that consists of:

  • A top bar
  • A right side bar
  • A canvas element that occupies the remainder of the screen space

These elements need to adjust to the browser window size changes while filling the page's width and height precisely.

Initially, I utilized flexbox to achieve this layout, but encountered an issue with the canvas content appearing extremely blurry.

To address this blurriness, I set the canvas resolution to its dimensions within a useEffect callback like so:

canvas.width = canvas.offsetWidth;
canvas.height = canvas.offsetHeight;

However, this solution caused the canvas to stop responding to page resizing - specifically, the canvas aspect ratio no longer adjusted based on the page dimensions, resulting in no changes when the page size decreased or increased.

I've created two examples to demonstrate this problem:

  1. This example on CodeSandbox features clear canvas content due to setting the canvas resolution, but does not respond to page resizing.
  2. On the other hand, this example on CodeSandbox adjusts to page resizing, yet suffers from blurry canvas content.

Would you happen to have any suggestions on how to resolve this issue? While I have come across similar inquiries, none of the solutions presented have proven to be effective in practice.

Answer №1

Before accessing the context, have you tried setting the height and width of the canvas element?

  useEffect(() => {
    let canvas = canvasRef.current;
    canvas.width = canvas.offsetWidth;
    canvas.height = canvas.offsetHeight;
    const context = canvas.getContext("2d");
    window.requestAnimationFrame(() => {
      draw(context, canvas);
    });
  }, [timer]);

You might want to consider using window.requestAnimationFrame when dealing with multiple component re-renders for animations

Here's a working example: https://codesandbox.io/s/react-playground-forked-upojf8?file=/plot.js:806-1079

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

A vertical divider from Material-UI embedded within a button

I'm trying to add a vertical divider between text and an icon in a button, but I can't seem to get it right. Here's my simplified component code: import React from 'react'; import Button from '@material-ui/core/Button'; i ...

Is there a solution for React Components child component rendering twice?

When I click on the Update Key button, Child1 component renders every time. How can I resolve this issue? Note: I have created three components - one parent component and two child components. When I click on the parent component's button to update th ...

Is it possible to establish multiple connections simultaneously using Stomp?

I have been utilizing the ng2-stomp-service in my Angular application. Is it advisable to set up multiple connections (not just multiple subscriptions)? In the past, I have always seen a single connection being established, with several subscriptions made ...

Maintain the HTML font color when printing - Issue with IE settings, not the printer

I've been struggling with this issue all day. Initially, I thought it was a problem with the print settings, but then I realized that it's actually the "Print background colors and images" option in IE causing the trouble. Here is the last test ...

What is preventing the element from being positioned at the bottom of the container?

I have a vertical bar chart with 5 different colored sub-containers. I'm trying to position the 'chicken' sub-container at the bottom of the bar without any bottom-margin, but so far my attempts have been unsuccessful. When I try using absol ...

PHP and AJAX failed to retrieve post data

I encountered some puzzling issues when attempting to send post data to a php file using xmlhttp request: Below is the javascript code snippet: function getHeaterDailyConfig(){ var oReq = new XMLHttpRequest(); var d = new Date() now = [d.g ...

What is the best way to prevent a jQuery hover event from adding a text-shadow to the CSS?

Currently, I am facing an issue with a jQuery event that triggers a text-shadow effect: $(".leftColumn").hover(function (){ $(".leftColumn h2").css("text-shadow", "0px 2px 3px rgba(0, 0, 0, 0.5)"); },function(){}); The problem arises when the text-shad ...

Ways to have a dropdown menu automatically close when opening another dropdown

Having an issue with managing multiple href links on a single page. When one link is clicked, it opens a dropdown, but if another link is clicked without closing the first one, the first dropdown remains open. How can I resolve this? I initially attempted ...

Switch between two tabs with the convenient toggle button

I have implemented 2 tabs using Bootstrap as shown below: <ul class="nav nav-tabs" role="tablist"> <li role="presentation" class="active"><a href="#home" role="tab" data-toggle="tab">CLient</a></li> <li role="presentatio ...

Is it possible for Penthouse to retrieve critical CSS while using javascript?

I am currently utilizing the laravel-mix-criticalcss npm package to extract the critical CSS of my website. This package leverages Penthouse under the hood, and you can configure Penthouse settings in your webpack.mix.js within the critical options. The ...

Discovering the distinction between arrays of JQuery objects

I have a task that requires the following steps: var elems = $('.lots-of-elements') Next, I need to make an AJAX request and then do this: var moreElems = $('.lots-of-elements') Finally, I am looking to identify only the new element ...

Invoking Angular component method using vanilla JavaScript

For my web application, I am utilizing Angular and require Bluetooth functionality on a specific page. I am implementing loginov-rocks/bluetooth-terminal (https://github.com/loginov-rocks/bluetooth-terminal) for establishing the Bluetooth connection, which ...

Why does JavaScript not wait for the completion of forEach and instead executes the next line immediately?

While creating my api in nodejs and attempting to push the mongoose return count to a newly created array, it does not wait for the forEach loop to finish before executing json.res() and returning a null response. However, when I use setTimeout(), the re ...

Error encountered: Failure to locate Yii2 class during an Ajax request

I've created a model class that represents a table in my database: <?php namespace app\models; use yii\db\ActiveRecord; class Pricing extends ActiveRecord { } Next, I attempted to utilize a simple PHP function in a separate fil ...

"Selectize component in Vue automatically closes the dropdown menu once an item is

Having trouble developing a straightforward selectize vue component. The issue arises when I select an option while using v-model within the component; the dropdown closes automatically. However, when I remove the v-model, the dropdown remains open until t ...

Changing the input to uppercase within Vue.js

I am looking to capitalize the input data from the user's full name model and would prefer if it is in Latin letters only. Utilizing Vue.js for Uppercase Conversion <p-input :value="value" @input="$emit('input', $event)&qu ...

Hide preloader in AngularJS once repeater has completed execution

Is there a way to hide a preloader div only after all data has finished loading in an ng-repeat loop? Check out this interactive example on Plunker: http://plnkr.co/edit/ilgOZzIy2axSi5Iy85C7?p=preview Here is the HTML code: <div ng-co ...

The CSS code isn't functioning properly on both desktop and mobile views

Here is what I desire to achieve: https://i.sstatic.net/8H4fv.png The CSS code I have is: And the HTML code looks like this: <body> <div class="contanier"> <div id="rightcol">Right Section</div> <div id="content">Cont ...

Error in React: The parsing process failed due to an unexpected token

I’m currently working on creating a Dynamic Material UI Flex box that dynamically generates new rows based on the backend. The concept is to close the current outer Box and initiate a new one depending on a certain flag. Here’s the code snippet that I ...

How can I obtain the true client IP address using Nginx?

I have a straightforward express app that has been containerized using Docker. You can find the repository here. In this setup, I utilized nginx as a reverse proxy. When accessing http://45.33.97.232:3000, it displays the actual server IP. However, if I v ...