Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Cách đặt vị trí dưới (perspectiveOrigin) cho phần tử 3D bằng JavaScript

Thuộc tính perspectiveOrigin (đặt trên **phần tử cha** có perspective) xác định vị trí "điểm nhìn" (vanishing point) cho các phần tử con được biến đổi 3D. Mặc định là 50% 50% (trung tâm).

Ví dụ minh họa

Mã sau đổi perspective-origin của container sang 20px 10% khi nhấn nút:

<!DOCTYPE html>
<html>
<head>
  <style>
    #div1 {
      position: relative;
      margin: auto;
      height: 200px;
      width: 200px;
      padding: 20px;
      border: 2px solid blue;
      perspective: 100px;
    }
    #div2 {
      padding: 80px;
      position: absolute;
      border: 2px solid blue;
      background-color: yellow;
      transform: rotateX(45deg);
    }
    #div3 {
      padding: 50px;
      position: absolute;
      border: 2px solid blue;
      background-color: green;
      transform: rotateX(30deg);
    }
  </style>
</head>
<body>
  <p>Thay đổi perspective origin của div1</p>
  <button onclick="setPerspectiveOrigin()">Đặt Perspective Origin Position</button>
  <div id="div1">DIV1
    <div id="div2">DIV2</div>
    <div id="div3">DIV3</div>
  </div>
  <script>
    function setPerspectiveOrigin() {
      document.getElementById("div1").style.perspectiveOrigin = "20px 10%";
      /* X: 20px từ trái, Y: 10% từ trên */
    }
  </script>
</body>
</html>

Cú pháp perspectiveOrigin

perspectiveOrigin: x-axis y-axis

  • x-axis: left | center | right | <percentage> | <length>
  • y-axis: top | center | bottom | <percentage> | <length>

perspectiveOrigin vs transformOrigin

Thuộc tính Đặt trên Chức năng Mặc định
perspectiveOriginContainer (có perspective)Điểm nhìn (vanishing point) cho toàn bộ cảnh 3D con50% 50%
transformOriginPhần tử con (có transform)Trục xoay/tâm co giãn của riêng phần tử đó50% 50%

Mẹo: Đặt perspectiveOrigin: 0 0 để tạo hiệu ứng nhìn từ góc trên-trái (như camera góc rộng).