Web/html

[HTML] 화면 크기가 달라져도 비율 유지하고 싶을 때

다닿 2024. 9. 24. 20:57
<script>
  function gcd(a, b) {
    while (b !== 0) {
      let temp = b;
      b = a % b;
      a = temp;
    }
    return a;
  }

  function get16to9Size(w, h) {
    const aspectRatio = 16 / 9;
    let x, y;

    if (w / aspectRatio <= h) {
      // 가로가 기준일 때
      x = w;
      y = Math.round(x / aspectRatio); // 16:9 비율에 맞춘 y 계산
    } else {
      // 세로가 기준일 때
      y = h;
      x = Math.round(y * aspectRatio); // 16:9 비율에 맞춘 x 계산
    }

    // x와 y의 최대공약수 구하기
    const g = gcd(x, y);

    // 최대공약수로 정수값으로 조정
    x = Math.round(x / g) * g;
    y = Math.round(y / g) * g;

    return { x, y };
  }

  // 예시 사용
  const { x, y } = get16to9Size(window.innerWidth, window.innerHeight);
  console.log(`16:9 화면 크기: ${x}x${y}`);
</script>

'Web > html' 카테고리의 다른 글

[HTML] 페이지 이동 history 남기지 않기 replace  (0) 2025.10.24