The rectangular shape extending beyond the boundaries of the canvas

I'm currently working on creating a rectangle within a canvas element. I've set the width of the div to match the width of the rectangle, but unfortunately, the rectangle is extending beyond the left side of the canvas container. My goal is to contain the canvas within the container and make its width equal to the width of the div.

Check out my code snippet below:

export default function App() {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const divRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const canvasReference = canvasRef.current;
    const divReference = divRef.current;
    const context = canvasReference?.getContext("2d");
    if (context && divReference) {
      context.strokeStyle = "#000";
      context.strokeRect(0, 0, divReference.clientWidth, 45);
    }
  }, []);

  return (
    <div className="App" ref={divRef}>
      <canvas className="timelineCanvas" ref={canvasRef}></canvas>
    </div>
  );
}

Feel free to explore the sandbox link

Answer №1

Ensure to specify the canvas dimensions in your CSS stylesheet. Additionally, opt for divReference.offsetWidth over divReference.clientWidth as it includes the border size too! 😊

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

In every browser except for Safari on iPad, a white X is displayed in the grey box. I'm wondering if the error lies with me or with Safari

When using Safari on my iPad, I noticed that the white X appears on the right-hand side of the black screen. Since this is the only version of Safari that I have, I am unsure if this issue is specific to iPads, Safaris, or just my device. Visit this link ...

Implementing class names for a component object in ReactJS: A step-by-step guide

For instance, imagine a scenario where you have a list component with each item containing a custom icon component. How can you set a class name for the object in the variable: const items = [ { name: "Example", icon: <Foo /> } ]; retu ...

Are React Arrays Capable of Accepting Boolean Inputs?

I am encountering issues with serializing my inputs and storing them in my API. I am struggling to get it to function properly. I would appreciate any advice or suggestions on how to achieve this using arrays or possibly a simpler method. I am facing diff ...

React - State array removing the last element instead of the element at the specified index

In my current setup, I have an array state that is populated with objects referred to as items: const [items, setItems] = useState([{name: "", toppings: []}]) However, when attempting to remove a specific index using this function: const removeItem ...

Learn how to dynamically pass a value from a prop to a router-link in Vue.js

I created a custom button component and decided to switch from using <a> tags to <router-link>. However, I encountered an error because the router-link was rendering before the prop received its value. To address this, I added an if statement b ...

Is it necessary to save the user's sign-in status in Local Storage in order to render the component (using React, Next.js, and Firebase Authentication)?

(Implementing Google Signin with Firebase and React(Next)) When a user signs in, the state is set to true. The home component and login component are rendered in index.js based on the state value. Initially, I stored this state in local storage, but I rea ...

What is the reason behind the header displaying a blue color with material UI?

Can you explain why the header is displaying in blue? I've tried changing the theme color, but it's not working. I'm expecting it to be red. You can view my code by following this link: https://material-ui.com/demos/app-bar/ Here is the cod ...

Guide on Showing Error Messages in a MERN Application

Having trouble displaying an error message for unregistered users attempting to sign in? I'm facing difficulty getting the frontend (reactjs) to show the error message sent from my backend (nodejs, express, MongoDB). Using redux to manage the react a ...

Transitioning from mui version 4 to version 5 leads to an error message: "TypeError: Cannot access 'keyboardDate' properties of undefined"

After updating from MUI v4 to version v5, I encountered failing tests with the following error: TypeError: Cannot read properties of undefined (reading 'keyboardDate') 17 | it("should render correctly without any errors", () =& ...

Deactivate the image button when no image has been chosen from the input field

Is it possible to have the image button disabled when no image is selected in the input field? The button should be inactive if an image is not chosen. import { useState } from "react"; const CommentForm = ({ handleSubmit, submitLabel }) => ...

Is an empty string equivalent to false in a boolean context?

I would appreciate further clarification on this subject. I have read several articles, but none have fully answered my questions. ...

Why is the format incorrect when the Angular 7 (Change)-Function on Input of type Date isn't functioning?

I am facing an issue with updating the date using key input and assigning the selected date to a property of my object. Below is the code I'm currently working with: <input type="date" [value]="dateTime()" (change)="setDate($event)"/> The dat ...

Erase the dynamically loaded page using ajax and conceal the div

Currently, I am utilizing the .on() method with jQuery to display a specific div, and also using .load() to fetch a particular div from a web page hosted on my server. My query is how can I close this div when clicking outside of it, along with removing i ...

Creating a variety of NextJS components

Currently delving into NextJS and aiming to showcase a website featuring my various projects created with it. A special "Tag" component functions as a button template that allows custom text passed through props: export default function Tag({val}) { r ...

What is the best way to update the state of a useState hook in React based on the value of an input button? I want the state to automatically change whenever the value of

On my page, I have 8 unique buttons. Each button should produce a different value when clicked. I am looking to create a useState hook where the state will be set to the value generated from the selected button. Additionally, I want to ensure that whenever ...

Crafting interactive image checkboxes

At present, the checkboxes in my application are quite basic with labels. However, our app designer has requested that we revamp this feature and make it more appealing by using clickable images that still function like checkboxes. Allow me to provide an ...

Ways to determine the height of a responsive div's background image

I have a container with a background image. Inside this container, there are additional elements like my navigation bar. My goal is to make the container have the same height as the background image. I've attempted the following: .bg { ...

Tips for utilizing the getServerSideProps function

I want to improve the SEO friendliness of my page by utilizing the getServerSideProps method. Despite searching online, I couldn't find a specific example that fits my situation. I am uncertain about how to proceed since I currently have a useEffect m ...

Play framework fails to apply style attributes correctly

When working with play-framework 2.3.x, I am in the process of creating a form and would like to show/hide it based on a model attribute. Typically, setting the style attribute manually using style = "display: none" and style = "display: block" works fine. ...

Duplicating an Angular 2 reactive form without retaining the original reference

I am facing a challenge with my reactive form where I need to round certain values when the form is submitted, without altering their appearance on the page. To achieve this, I devised a method that generates a new form, rounds the specified values, and t ...