Creating dynamic height based on width using JavaScript

I'm trying to make a rectangle responsive based on the width of the window.

This is my current logic:

aspectRatio = 16 / 9
win = {
    width: window.innerWidth,
    height: window.innerHeight,
}

get browser() {
    const width = this.win.width - 250
    const height = width / this.aspectRatio

    return {
        width,
        height,
    }
}

To calculate the width, I subtract the sidebar width (250) from win.width.

For the height, I divide the width by the aspectRatio.

However, when the window size is reduced to around 700px, it results in a height of 0.

My application can be seen here:

https://i.stack.imgur.com/rqpVc.png

Demo →

CodeSandBox → https://codesandbox.io/s/add-padding-to-centered-canvas-with-sidebar-gqhhl

I want the papayawhip rectangle to be responsive. What algorithm should I use? I'm using Canvas with KonvaJS but the logic is written in JavaScript.

How can I make it responsive and maintain proportionality as the height shortens quickly?

Answer №1

Below is the approach I took:

function App() {
  const storage = useStorage();
  const { victory, navigator, aspect } = storage;
  const offset = 50;

  const widthOfRect = navigator.width - offset;
  const heightOfRect = widthOfRect / aspect;

  return (
    <div className="flex">
      <div id="sidebar">
        <h1 className="text">
          Center <span>papayawhip</span> Canvas
        </h1>
      </div>
      <Stage width={navigator.width} height={navigator.height} id="konva">
        <Layer>
          <Rect
            width={widthOfRect}
            height={heightOfRect}
            x={offset / 2}
            y={(victory.height - heightOfRect) / 2}
            fill="papayawhip"
          />
        </Layer>
      </Stage>
    </div>
  );
}

Additionally, I updated the storage setup so that navigator gives back the canvas area:

get navigator() {
        const width = this.victory.width - 250
        const height = this.victory.height

        return {
            width,
            height,
        }
}

Demo: https://codesandbox.io/s/react-konva-responsive-canvas-ogk1n

Answer №2

Initial Answer

width: 100%;
padding-top: 56.25%; /* Maintaining a 16:9 Aspect Ratio */

Alternative Approach

padding-top: calc(9 / 16 * 100%);

Answer №3

If you find yourself in a situation where you need to make CSS changes, but your component is buried 3 levels deep, don't worry! You can easily access the CSS file that is already imported next to your .tsx file.

To achieve this, simply add the following line of code at the end of your file:

import "./styles.css"

This trick, borrowed from @deadcoder's solution for resolving ratio issues, will ensure that your component displays correctly across different screen sizes. Take note of the responsive breakpoints provided below to maintain the aspect ratio and prevent shrinking to nothing.

canvas {
  width: 100%;
  padding-top: 56.25%; /* 16:9 Aspect Ratio */
}

@media screen and (max-width: 1200px) {
    canvas {
      width: 100%;
      height: 400px;
      padding: 0; /* reset the ratio for smaller sizes so you can crop it */
    }
}
@media screen and (max-width: 600px) {
    canvas {
      width: 100%;
      height: 200px;
      padding: 0; /* reset the ratio for smaller sizes so you can crop it */
    }
}

Additionally, consider assigning an ID or class to the canvas element for easier targeting.

If you are still experiencing issues with the height disappearing too quickly, try using the entire area as the canvas or utilizing a background image instead.

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

Attempting to squeeze a lengthy word into a small span

Apologies for my poor English. I tried searching for an answer online but couldn't find a solution. Maybe I'm just not able to figure it out myself. All I need is to make those long words fit inside a button. This is how it currently looks. My ...

Modifying form data when submitting a form

Is there a common or widely-used method for modifying or adding form values before they are serialized and sent to the server upon form submission? I'm looking for a way to change or add these values without having to recreate them. I've come ac ...

Utilizing React with Material UI, implement a Select component while disabling the scroll lock and ensuring the menu is positioned relative to

import React from "react"; import "./styles.css"; import Input from "@material-ui/core/Input"; import MenuItem from "@material-ui/core/MenuItem"; import FormControl from "@material-ui/core/FormControl"; import Select from "@material-ui/core/Select"; cons ...

The production build encountered an error after upgrading Angular due to a problem with document.documentElement.setAttribute not being recognized

Recently, I updated my application to Angular 16 and the upgrade was successful. The application is running smoothly without any issues. However, when I attempted to run the command for a production build, ng build --configuration=production I encountere ...

Configuring CORS in an Angular JS controller

Having a controller with a service that retrieves JSON from another server, I encountered the following issue: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http:somesite.com. This can be fixed by moving the ...

Strategies for handling uncaught promise rejections within a Promise catch block

I'm facing a challenge with handling errors in Promise functions that use reject. I want to catch these errors in the catch block of the Promise.all() call, but it results in an "Unhandled promise rejection" error. function errorFunc() { return ne ...

Encountering Rendering Issues with EJS Post HTML Conversion

After working on a much larger project for over a month, I'm now six hours into troubleshooting and everything is starting to blend together. Prior to switching to EJS, everything was working perfectly. I'm not looking for someone to solve the ...

Difficulty activating JavaScript function - unsure of proper implementation

I'm having trouble with calling a function instead of an alert in my code. I tried using FunctionsName(); and removing the alert(''); but it doesn't seem to be working for me :( Could someone please take a look at the following code an ...

Consistently encountering the error message "(0 , _reactDom.h) is not a function" or "h is not defined"

I'm currently in the process of developing an app that makes use of electron, react, redux, and several other technologies. At the moment, I have included electron, react, electron-compile, and babel in the project. Redux is installed but has not been ...

Switch between pages within a reactjs application by utilizing react router

Greetings! I am currently diving into the world of reactjs and experimenting with navigation from one page to another by simply clicking on a link through react router. In my home.js file, I have listed out some interesting places and I aim to click on one ...

Angular 7 three-dimensional model display technology

Looking for advice on creating a 3D model viewer within an Angular 7 project. Currently using the model-viewer web component in JavaScript with success. How can I replicate this functionality and viewer within my Angular 7 application? ...

The JavaScript fetch API failed to receive a response after sending data via a 'POST' request to a Django server

Currently, I am in the process of developing a poll application that utilizes both Django and React. My approach involves using the fetch API to send POST requests to my Django server and receive detailed information in return for further processing. For a ...

Updating JQuery dropdown menu fills in additional form fields based on selection

I have a dropdown menu (select) that is dynamically generated using JSON data from a PHP script and JQuery. Please refer to the image under the Components label. The select menu displays the Component name and Component ID as values. I would like to use a ...

Is this included in the total number of reads?

Following my query with CollectionsGroup, I attempted to retrieve the information of the parent's parent like this: db.collectionGroup('teams').where('players', 'array-contains', currentUser.uid).get().then(function(snaps ...

Improving React code by using conditional statements such as IF and Else

Currently, I am delving into the world of React and have managed to devise some logic for rendering a DIV. However, upon reflection, it has become evident that there is redundancy present in my code structure and I am uncertain about how to efficiently ref ...

Using JQuery to create animations with fadeIn and fadeOut effects is a great way to

As a complete newbie taking my first steps in front-end development, I spent most of my day trying to work out an animation function but couldn't quite get it right. Below are the snippets of HTML, CSS, and JavaScript codes: <!DOCTYPE html> < ...

I'm having trouble getting my object to display using ng-repeat in Angular. Can anyone help me understand what I'm missing?

My goal was to add an object to an array upon clicking an event, which I successfully achieved. However, the objects are not displaying in the ng-repeat as ordered. Can you help me figure out what's missing? angular.module('app', []); an ...

Utilize JavaScript's $.post function to export PHP $_POST data directly into a file

After spending hours trying to figure this out, I've come to the realization that I am a complete beginner with little to no knowledge of what I'm doing... The issue I'm facing is related to some JavaScript code being triggered by a button ...

Encountering an error with $mdDialog.alert

I am attempting to activate an Alert Dialog using Angular Material Design. Within my controller, I have: angular.module('KidHubApp') .controller('ActivityCtrl', ['$scope','$meteor', '$stateParams', &apo ...

Leverage the power of HTML, CSS, and Bootstrap within Visual Studio 2022 when developing with

Could someone help me figure out how to implement HTML, CSS, and JavaScript design in Visual Studio 2022 while utilizing ASP.NET controls for coding purposes? I am encountering difficulties in starting my work on a website project. Any assistance would be ...