JavaScript calculation: how tall is the image?

Can you calculate the CSS height of an image with a width of 3px?

The original image is:

- Height: 400px

- Width: 800px

I have attempted to:

Convert the 3px into a percentage based on the original image width:

function getPercentageOfWidth(v){
return 100 * v / originalImageWidth; // Original image width
}

function getHeightFromPercentage(v){
return   v / 100 * originalImageHeight; // Original image height
}

var imgWidthPercentage = getPercentageOfWidth(3);
var imgHeightFromPercentage = getHeightFromPercentage(imgWidthPercentage);

// Unfortunately, the calculated height was incorrect

Any assistance would be greatly appreciated.

Answer №1

To calculate the ratio between width and height, follow this formula:

const ratio = originalWidth / originalHeight;

Next, to determine the width for a different height, use the following equation:

const newWidth = newHeight * ratio;

For instance, in the given scenario:

const originalHeight = 800;
const originalWidth = 400;
const ratio = originalWidth / originalHeight;
const newHeight = 3;
const newWidth = newHeight * ratio;
console.log(newWidth);

Remember to consider Sebastian's suggestion that using CSS's aspect-ratio might be a viable alternative.

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

Adjust the size of a div container depending on the content it holds

If the element div.PageheaderDescription does not contain any img or div#cat-text, I'd like the height to be set to 0px to eliminate any white space. Below is my CSS code: .PageHeaderDescription { height: 320px; position: relative; width ...

Not receiving connections on localhost port 3000

Our team has successfully created a basic Express Node website https://i.stack.imgur.com/5fwmC.png We attempted to run the app using DEBUG=express_example:* npm start https://i.stack.imgur.com/NI5lR.png We also tried running it with node DEBUG=express_ ...

Could anyone help me locate the section in the MUI documentation that explains the correct syntax for the commented code lines I am working on?

Before proceeding, please note that the ThemeProvider with theme={theme} has already been provided. Now, I will share two distinct sets of code files. These files contain sections commented out because they are not functioning as intended when implementing ...

Obtain the index by clicking on an element within an HTMLCollection

Within my HTML code, I have 9 <div> elements with the class ".square". I am looking to make these divs clickable in order to track how many times each one is clicked and store that information in an array. For example, if the fifth <div> is c ...

Issue with AngularJS script halting when reaching factory function that returns a promise

I have been working on a beginner project that is essentially a simple task manager (similar to those todo list projects). I created a user login page for this project and here is how it functions. There are two functions, siteLogin() for logging in, and ...

What is the method for obtaining the viewModel in a Knockout component?

I need to prepopulate a knockout component when the document is ready. This is the code I have written: function Finding(id, trigger) { var self = this; self.id = ko.observable(id); self.trigger = ko.observable(trigger); } function FindingVi ...

What causes the while loop in a threejs render function to not refresh each frame?

I'm struggling with handling an array of 8 cubes, each only 1 pixel tall. When a button is pressed, I want them to smoothly animate to a new height using a while loop. Here's my current implementation: if (buttonPressed) { console.log(' ...

Using val() on a checkbox will give you an element, not a string literal

How can I retrieve only the literal values of all checked checkboxes without any additional data? My current approach is: $('input:checked').map(function() { return $(this).val(); }) The result that I am getting looks like this: e.fn.init[1]0 ...

The value from the angular UI bootstrap datepicker is unavailable when using a JQuery expression

I have a question regarding the datepicker feature from the Angular UI bootstrap library. The documentation can be found here. After selecting a date using the datepicker, I am facing an issue with retrieving the text input using jQuery expressions. When ...

ExpressJS route encountering issues with GET method functionality

I'm facing an issue with my code where the function is not running inside the specific routing when trying to retrieve data using /:user. Can someone help me identify the mistake in the following implementation? const express = requi ...

Adjusting the transparency of numerous elements using JavaScript or jQuery

My task involves creating a large form where elements initially have an opacity of 0.5, and when a button is clicked, the opacity changes to 1.0. While I can achieve this using JavaScript, I want to find a more efficient way by avoiding individual if state ...

Before the async function, make sure to set the value using React's useState

Exploring the world of react context api for the very first time. Below is my react code utilizing the context api: const [valChanged, setValChanged] = useState(false); async function modalSave() { await setValChanged(true); // STEP 1 await o ...

Get a calendar that displays only the month and year

I am looking to incorporate two unique PrimeFaces calendars on a single page. The first calendar will display the date, while the second one will only show the month and year. To achieve this, I have implemented the following JavaScript and CSS specifica ...

"Utilize a specific parameter in the npm run script for enhanced

Is it possible to pass a named parameter to an npm run script in order to achieve the following functionality? "scripts":{ "say-hello":"echo $greeting && ls" } npm run hello --greeting=hello The desired outcome is to replace the $greeting ...

What is the process for comparing two objects in TypeScript?

There is a unique class named tax. export class tax { private _id: string; private _name: string; private _percentage: number; constructor(id: string = "", taxName: string = "", percentage: number = 0) { thi ...

Working with Node.js: Implementing a method callback within a loop

What is the best way to call a method with a callback in a loop? Let's say you have to make multiple calls to http.get but you want to ensure that only one request is waiting for a response at a time (to avoid overwhelming the server) http.get(url, ...

Mastering the art of utilizing defer/async attributes in script tags effectively

When I add the "defer" attribute to all external js files, Owl Carousel fails to load and shows an error that "$" is not defined. However, if I remove the defer attribute from the script tag, everything works fine without any errors. Unfortunately, I am un ...

Having difficulties with JavaScript's if statements

I'm facing an issue with my JavaScript code that is meant to modify the value of a price variable and then display the updated price. The problem arises when I have multiple select options, as the price only reflects the ID of the last statement. Here ...

Is there a way to modify this within a constructor once the item has been chosen from a randomly generated array?

If I use the following code: card01.state = 3; console.log(card01); I can modify the state, but I'm interested in updating the state of the card chosen by the random function. class Item { constructor(name, state) { this.name = name; thi ...

"Utilizing AJAX to fetch and showcase API key along with its corresponding values within an HTML

Seeking assistance with a task. I am currently working on displaying API JSON key and value data in a formatted CSS layout on an HTML webpage. My approach involves making an AJAX call to a Node.js server to retrieve the data. While I have successfully ret ...