The React canvas within a CSS grid is not taking up the entire space

I'm currently developing a line plotter in React. This "line plotter" needs to be contained within a CSS grid item. I am utilizing the <canvas> element to draw the lines, but I'm unsure if this is the best approach. Is there a more efficient method I should consider?
More importantly, my canvas is not occupying the full size of the grid item. Is there a way to achieve this and also ensure that the origin of the canvas is at the center?
Here's a snippet of my code:

const Canvas = props => {

    const { draw, settings, ...rest } = props
    const canvasRef = useRef(null)

    useEffect(() => {

        const canvas = canvasRef.current
        const context = canvas.getContext('2d')
        draw(context, settings)
    }, [draw])

    return (
        <div className={"fractal_tree_canvas"}>
            <canvas ref={canvasRef}/>
        </div>
    )
}

And here's the accompanying CSS:

.fractal_tree_canvas {
  height: 100%;
  width: 100%;
  grid-row: 2;
  grid-column: 2;

}

Finally, here's the grid setup:

.fractal_tree_screen {
  background-color: #e7e7e7;
  display: inline-grid;
  position: relative;
  width: 100vw;
  height: calc(100vh - 65px);
  grid-template-columns: 5% 50% auto 5%;
  grid-template-rows: 6% 1fr 6%;

}

Despite my efforts, the canvas size remains stuck at 300x150. How can I ensure it fills the entire grid item?

Answer №1

<canvas does not respond to CSS styling like other elements do. To adjust its dimensions, you must specify the width and height attributes in the HTML code.

If these attributes are left undefined, the canvas will default to a size of 300x150, which seems to be the case in your situation.

In React, you can calculate the desired dimensions and apply them directly within JSX.

To handle resizing, you will need to listen for resize events, adjust the canvas attributes accordingly, and redraw the content as needed.

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

What are the best methods for capturing individual and time-sensitive occurrences within a service?

I am currently working on structuring the events within a service to enable a mechanism for subscribing/unsubscribing listeners when a controller's scope is terminated. Previously, I utilized $rootScope.$on in this manner: if(!$rootScope.$$listeners[& ...

Troubleshooting a problem with a for loop in JavaScript while developing a personalized jQuery paging

Seeking assistance with some javascript, and perhaps it's just a Friday thing, but I've hit a roadblock... I'm currently in the process of creating a custom jQuery carousel and trying to implement dynamic paging. To simplify the problem (I ...

I am unable to view the most recent version of json-parse-better-errors on NPM

I've encountered an issue while trying to execute the npx create-react-app command on my local machine. The script fails during the installation process of json-parse-better-errors. It seems like it is looking for version 1.0.2, which is stated as the ...

The Challenge of Dynamic Angular Components

Upon triggering the blur event of the contenteditable div, I observe changes and dynamically generate new strings with additional spans to update the same div accordingly. However, a challenge arises when all text is deleted from the contenteditable div, r ...

Executing a JavaScript function with no event

This particular code snippet is taken from a.jsp: <script type="text/javascript" > function checkDates(date1, date2) { var x = date1.split('/') var y = date2.split('/') var firstDate = new Date(x[2],x[0 ...

The href attributes are not being retrieving correctly

I'm currently working on extracting the URLs for each restaurant listed on this page and have developed a Python script for this purpose: import time from selenium import webdriver from selenium.webdriver.common.keys import Keys browser = webdriver ...

The ng-repeat function is unable to fetch data from a JSON file

Within my AngularJS framework template, I have the following snippet of html code: <ul class="sb-parentlist"> <h1 class={{headerClass}}> Popular</h1><div data-ng-repeat="data in data track by $index"> <li> ...

Unable to trigger click event

I apologize for asking the same question again, but I'm really struggling with this seemingly easy (or difficult?) code problem. Despite trying out Rory McCrossan's solution from here, it still doesn't seem to work for me. Can someone please ...

Passing state data from parent to child components in React

I am currently facing an issue with binding the state of a parent component to a child component. Here is a snippet of the code: Parent Component: class ParentForm extends React.Component { constructor(){ super(); this ...

Issue with HTML/CSS: rectangle doesn't scroll as expected

I'm in the process of developing a new website and I want to include a top bar and footer with some unique elements on it. Additionally, I am looking to create a rectangular area where I can input text. After writing the following code snippet, this ...

The outcome of the Python web crawling did not meet our expectations

After using Selenium to scrape web data, I encountered an issue where it only displayed 96 out of 346 products instead of the expected 346. Does anyone have suggestions on how to fix this problem? The crawling code is placed right after the loop for clicki ...

Remove user from axios response interceptor for server-side component

In my Next.js 14 application, I have set up axios interceptors to handle errors. However, I need assistance in logging out the user and redirecting them to the '/login' page if any error occurs. Below is the code snippet for the interceptors: axi ...

Attributes for 'v-bind' directives must have a value specified

Struggling to implement a tree structure in vue.js and encountering an issue with element props. Any assistance would be greatly appreciated. I've attempted using :content="{{tempCont}}" as well as content="{{tempCont}}", but neither approach proved ...

What is the best way to showcase nested array JSON data in an HTML Table?

https://i.stack.imgur.com/OHL0A.png I attempted to access the following link http://jsfiddle.net/jlspake/v2L1ny8r/7/ but without any success. This is my TypeScript code: var viewModel = function(data){ var self = this; self.orders = ko.observableArr ...

"Looking for a way to automatically close the <li> tag in Vuejs when clicked outside

clickOutside: 0, methods: { outside: function(e) { this.clickOutside += 1 // eslint-disable-next-line console.log('clicked outside!') }, directives: { 'click-outside': { ...

Creating a dynamic search bar using Ajax with support for multiple keywords

I recently attempted to create an ajax search bar for my website. It functions perfectly with a single keyword, however, I'm facing some difficulty when trying to make it work with two keywords. I thought about parsing the data in the input field, but ...

Guide on capturing JSON objects when the server and client are both running on the same system

I created an HTML page with a form that triggers JavaScript when submitted using the following event handler: onClick = operation(this.form) The JavaScript code is: function operation(x) { //url:"C:\Users\jhamb\Desktop\assignmen ...

The length function appears to be signaling an unanticipated error

Recently, I encountered an issue with the code execution. Although the code appears to be functioning correctly, it is throwing an uncaught error. Is there a reason for concern regarding this situation? var xmlhttp = new XMLHttpRequest(); xmlhttp.onread ...

Is it possible to merge neighboring text nodes within the DOM using JavaScript?

If I come across a sentence within the webpage's DOM that includes 3 separate text nodes followed by additional elements like BOLD or ITALIC, is there a simple method to merge these text nodes into one? Having adjacent text nodes serves no purpose and ...

Ensure that all checkboxes are only selected within a single table

I have a challenge with selecting all check boxes in multiple tables when the header check box is selected. I am attempting to achieve this using jQuery without needing to parse or pass in the table id. Currently, when I select one header check box, all th ...