給予寬度,算出圖片等比例高度

Here’s a simple JavaScript example to calculate the proportional height of an image when you set a fixed width:

function calculateProportionalHeight(originalWidth, originalHeight, newWidth) {
  const newHeight = (originalHeight * newWidth) / originalWidth;
  return newHeight;
}

// Example usage:
const originalWidth = 800;
const originalHeight = 600;
const newWidth = 400;

const newHeight = calculateProportionalHeight(originalWidth, originalHeight, newWidth);
console.log(`The proportional height for the new width is: ${newHeight}px`);

Explanation

  • The calculateProportionalHeight function takes the original width, original height, and the new width as arguments.
  • It calculates the new height using the formula we discussed and returns it.

In this example, if the original dimensions are 800×600, and you set a new width of 400, the function will calculate the new height that maintains the image’s aspect ratio.

https://chatgpt.com/share/6708fb61-3764-8001-b612-cc70253e169e