Determining the size of the axis in correlation to a set constant length

Basic Concept

I am currently developing a small tool designed to assist with geometric calculations for print-related items.

Project Overview

In this tool, users are asked to input the width and height of a box, represented visually as a CSS-based box, through two input fields labeled w and h.

The challenge lies in accurately displaying the measurements within a limited space, with the box constrained to a maximum size of 69 x 69 pixels.

To address this, my goal is to scale the dimensions of the box proportionally based on the longer of the two input values, while ensuring that it does not exceed the maximum size.

Technical Approach

Despite not being mathematically inclined, I have devised a function to achieve this purpose:

updateRectBox: function(w, h){

    var max_x = 69;
    var max_y = 69;
    var factor, x, y;

    factor = w / h;

    if (w == h) {
        x = max_x;
        y = max_y;
    } else {
        if (w > h) {
            x = max_x;
            y = (factor > 1 ? max_y / factor : max_y * factor);
        } else {
            x = (factor > 1 ? max_x / factor : max_x * factor);
            y = max_y;
        }
    }

    jQuery('#rect').css({
        'width': (x) + 'px',
        'height': (y) + 'px'
    });

}

While this function serves its purpose effectively, I believe there is room for optimization and simplification.

Seeking Refinement

Considering my limitations in mathematical expertise, I am reaching out for suggestions on refining and streamlining the code for a more elegant implementation. I have provided a working fiddle to facilitate testing and experimentation.

Answer №1

This function successfully achieves its goal. While there are potentially more elegant ways to write it, the basic concept remains the same.

The concept here is resizing a box with dimensions (w × h) to fit within a (69 × 69) box by scaling it accordingly.

In order for the box to fit within a (69 × 69) box, both the width and height of the original box (w × h) must be less than or equal to 69. Let's assume we scale the box by a factor of s. The new box dimensions will be (s * w × s * h). Based on this constraint, we can derive the following inequalities:

s * w <= 69 and s * h <= 69. Solving for s, we get:

s <= 69 / w and s <= 69 / h. To satisfy both conditions, we can rewrite this as:

s <= min( 69 / w, 69 / h). To maximize the scaling and fill the region completely, we set s = min( 69 / w, 69 / h).

The provided code achieves the same objective using if-statements. A more concise version can be written as follows:

updateRectBox: function(width, height) {

    // define maximum width and height for box
    var max_width = 69;
    var max_height = 69;
    var scale = Math.min( max_width / width, max_height / height );

    var x = scale * width;
    var y = scale * height;

    // setting the box element's properties
    jQuery('#rect').css({
        'width': x+'px',
        'height': y+'px'
    });
}

Changing the variable names for clarity improves readability (e.g., using explicit names like width and height).

While there may not be significant performance discrepancies between the original code and this revised version, the use of Math.min has been shown to be faster in certain tests.

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

Obtaining values from multi-dimensional arrays with JavaScript and node.js

I have a data structure like this: let arr = [ ['animal','lion'], ['plant','rose'], ['tree','coconut'], ] I want to reformat it to look like this: ['animal','lion' ...

Tips for preventing harmful messages in a chat room app

As I am working on a chat room website, users are able to input any content they want into the entry field and then send it to all online users. However, I have concerns about security - what if malicious individuals try to inject harmful HTML or JavaScrip ...

Is there a simple method to add animation to a group of images displayed on click using JQuery?

Here is my JavaScript code that I'm currently using: $(document).ready(function() { $(".button-list .next").click(function() { project = $(this).parents().filter(".projektweb").eq(0); currentimg = project.find(".im ...

Create an illustration of a canvas interacting with a database image source, but failing to display local images

When attempting to load an image onto a canvas, I encountered an issue. My code works without any errors when I use image.src="https://somelink", but throws a GET error when I try to import with image.src="../public/vercel.svg. Below is my c ...

Troubles with Promise.all and json() in JavaScript causing errors being logged as "invalid function"

I'm experiencing some difficulties with the "Promise.all" method. Essentially, I have an array of URLs (here is a simple one if you want to test it: const urlArray = [ "https://coverartarchive.org/release/985adeec-a1fd-4e79-899d-10c54b6af299&qu ...

Employing Visual Composer within WordPress has resulted in the raw JavaScript not being properly applied to my raw HTML code

Sharing some code that functions properly in my browser and I want to implement on my WordPress page: <!doctype html> <html lang="en"> <head> <meta charset="UTF-8> <!-- Getting jQuery --> <script src="http://ajax.goog ...

Retrieving the values of multiple selected options from various select fields simultaneously

Picture having a dynamic number of select fields (the value of this variable is not fixed). I am looking to extract the values of the selected option from each select field using jQuery (or vanilla JavaScript). This is my approach: var cars = $(".sele ...

Issue encountered when attempting to invoke a PHP function using Javascript through AJAX

I'm currently working on incorporating a PHP function into my HTML file using Ajax (which also contains JavaScript). My goal is to retrieve all locally stored JSON files. I've been following a guide at , but I'm facing some challenges. When ...

NextJS is throwing an error stating that the element type is invalid. It was expecting either a string for built-in components or a class/function for composite components, but instead received an object

I encountered the following issue: Error - Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but received an object. Here's the code from my \components\LayoutWrapper.js: i ...

What is the best way to ensure that the bootstrap nav tab content fits perfectly on one line?

Check out this bootstrap navbar example You can see a screenshot here. <ul class="nav nav-tabs" style="display: inlne-block"> <li class="nav-item" style="text-align: center; display: inline;"> <div> <a class="nav ...

I need the language chosen using Lingui's Language Switcher (i18n) to persist throughout the app, even after a refresh

I have been experimenting with Lingui for internationalization (i18n) in my app. I followed the documentation and tutorial to create a language switcher, but I am unsure how to set it up so that the selected language persists throughout the app even after ...

removing an item from a nested array through the use of the filter() method

I have been struggling to remove an element with a specific ID from a nested array. Are there any suggestions on how to effectively utilize the filter() method with nested arrays? The goal is to only eliminate the object with {id: 111,name: "A"}. Below ...

Ways to emphasize the chosen row within angular js 4

Today, I am exploring an example to understand how data can be passed from a parent component to a child component and back. Below are the files that I have used for this example. I have included both the HTML and TypeScript files for both the parent and ...

Preventing Columns in SlickGrid from Being Reordered

Is there a way to prevent specific columns in SlickGrid from being reordered? I have tried looking for a solution but couldn't find one. Unlike the 'resizable' option, there doesn't seem to be an option for each column to allow or disal ...

What is the most effective method of testing with jest to verify that a TypeScript Enum list contains all the expected string values?

Recently, I created a list of enums: export enum Hobbies { Paint = 'PAINT', Run = 'RUN', Bike = 'BIKE', Dance = 'DANCE' } My goal is to iterate through this list using Jest and verify that all the string ...

Manipulating events through adjusting values of a JQuery-UI range-slider

My range-slider's values are being set with the code: $('...').slider( 'values', [ 0, 10000 ] );. However, I am facing an issue where this line triggers the change( event, ui ) event twice. Is there a way to ensure it only triggers ...

Building a simple messaging platform with the power of Socket.io and Node.js

After following the guide at http://socket.io/get-started/chat/, I attempted to create a basic chat application. However, upon running npm install --save socket.io I encountered the error message below. How can I resolve this issue? npm WARN package.jso ...

Encountering an issue with finding the module `scheduler/tracing` in React Native

Encountering an error during the react-native run-android process: Error: Unable to resolve module `scheduler/tracing` from `/Users/miftahali/projects/react/appscustomec/node_modules/react-native/Libraries/Renderer/oss/ReactNativeRenderer-dev.js`: Module ...

Best practice for managing asynchronous calls and returns in TypeScript

I’ve recently started working on an Ionic 4 project, delving into the realms of Javascript / Typescript for the first time. Understanding async / await / promise seems to be a bit challenging for me. Here’s the scenario: In one of the pages of my app ...

Error Occurs While Getting Request Parameters with Ajax Post and Express.js

When utilizing ajax to send data from a JavaScript frontend to an Express.js backend server, I am having trouble retrieving the posted data in the API method of my express.js. Below is the code where I attempt to parse the request data. Your assistance i ...