萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 實現 360° 全景圖拖拽旋轉:預加載、觸屏/鼠標雙模、無限循環

效果原理

準備一組連續拍攝的圖片序列(如 60 幀),通過鼠標/觸屏水平拖拽切換幀,實現物體 360° 旋轉視覺效果。核心邏輯:水平位移量映射到幀索引。

完整實現代碼

1. HTML 結構

<div id="viewer" class="viewer">
  <img id="panoramaImg" src="" alt="全景圖">
</div>
<div id="loading" class="loading"><span>0%</span></div>

2. CSS 樣式

.viewer { 
  position: absolute; left: 50%; top: 50%; 
  width: 1024px; height: 768px; 
  margin: -384px 0 0 -512px; 
  display: none; 
}
.viewer img { width: 100%; height: 100%; border-radius: 8px; border: 5px solid #555; user-select: none; }
.loading { position: fixed; left: 0; top: 0; width: 100%; height: 100%; background: #333; color: #fff; display: flex; align-items: center; justify-content: center; z-index: 999; }
.loading span { font: 50px Arial; }

3. 核心 JS:預加載 + 拖拽邏輯

(function($) {
  // 預加載工具
  function preloadImages(urls, onProgress, onComplete) {
    var loaded = 0, total = urls.length;
    urls.forEach(function(url) {
      var img = new Image();
      img.onload = img.onerror = function() {
        loaded++;
        onProgress(loaded, total);
        if (loaded === total) onComplete();
      };
      img.src = url;
    });
  }
  
  // 360 拖拽插件
  $.fn.drag360 = function(images, options) {
    var opts = $.extend({
      sensitivity: 40,      // 像素位移觸發切換幀
      autoRotate: false,    // 自動旋轉
      autoRotateSpeed: 200  // ms/幀
    }, options);
    
    var $img = this;
    var len = images.length;
    var current = 0;
    var startX = 0;
    var dragging = false;
    var autoTimer = null;
    
    function showFrame(index) {
      current = (index % len + len) % len; // 循環索引
      $img.attr('src', images[current]);
    }
    
    function startAuto() {
      if (autoTimer) return;
      autoTimer = setInterval(function() {
        showFrame(current + 1);
      }, opts.autoRotateSpeed);
    }
    
    function stopAuto() {
      clearInterval(autoTimer);
      autoTimer = null;
    }
    
    // 鼠標事件
    $img.on('mousedown', function(e) {
      e.preventDefault();
      dragging = true;
      startX = e.pageX;
      stopAuto();
    });
    
    $(document).on('mousemove.drag360', function(e) {
      if (!dragging) return;
      var dx = e.pageX - startX;
      if (Math.abs(dx) > opts.sensitivity) {
        showFrame(current + (dx > 0 ? 1 : -1));
        startX = e.pageX;
      }
    }).on('mouseup.drag360 mouseleave.drag360', function() {
      dragging = false;
      if (opts.autoRotate) startAuto();
    });
    
    // 觸屏事件
    $img.on('touchstart', function(e) {
      var touch = e.originalEvent.touches[0];
      dragging = true;
      startX = touch.pageX;
      stopAuto();
    }).on('touchmove', function(e) {
      if (!dragging) return;
      e.preventDefault(); // 防止頁面滾動
      var touch = e.originalEvent.touches[0];
      var dx = touch.pageX - startX;
      if (Math.abs(dx) > opts.sensitivity) {
        showFrame(current + (dx > 0 ? 1 : -1));
        startX = touch.pageX;
      }
    }).on('touchend touchcancel', function() {
      dragging = false;
      if (opts.autoRotate) startAuto();
    });
    
    // 初始化顯示第一幀
    showFrame(0);
    if (opts.autoRotate) startAuto();
    
    return this;
  };
})(jQuery);

4. 頁面初始化

$(function() {
  // 禁用選中/右鍵/拖拽默認行為(可選)
  $(document.body).attr({
    'onselectstart': 'return false;',
    'oncontextmenu': 'return false;',
    'ondragstart': 'return false;'
  }).css('-webkit-user-select', 'none');
  
  // 圖片序列(實際項目建議從後端獲取或配置文件讀取)
  var frames = [];
  for (var i = 6; i <= 360; i += 6) {
    var num = i < 100 ? '0' + (i < 10 ? '0' + i : i) : i;
    frames.push('drag/shiwai_ceshi' + num + '.jpg');
  }
  
  // 預加載並啟動
  preloadImages(frames, function(loaded, total) {
    $('#loading span').text(Math.ceil(loaded / total * 100) + '%');
  }, function() {
    $('#loading').fadeOut();
    $('#viewer').fadeIn();
    $('#panoramaImg').drag360(frames, {
      sensitivity: 30,
      autoRotate: true,
      autoRotateSpeed: 150
    });
  });
});

性能優化建議

  • 圖片壓縮:WebP 格式 + 適當質量(70-80%),單幀控制在 50-100KB
  • 幀數權衡:360° 建議 36-72 幀(每 5-10° 一幀),過多增加加載時間
  • 懶加載:首屏只載入首幀,其餘 IntersectionObserver 或滾動時加載
  • GPU 加速:img { will-change: transform; } 或使用 transform: translateZ(0)
  • 請求合併:精靈圖或 HTTP/2 多路複用減少連接開銷

現代替代方案

方案優點缺點
Three.js + 全景貼圖真 3D、支援縮放、熱點、VR體積大、學習曲線陡
Pannellum / Photo Sphere Viewer成熟庫、支援熱點、自動旋轉、全屏需引入庫文件
CSS 3D Transform + 拖拽無圖片序列、單張全景圖即可邊緣畸變、非真實拍攝

總結

基於圖片序列的 360° 產品展示,預加載 + 拖拽幀切換 是最兼容、最輕量的方案。本文插件支援鼠標/觸屏、靈敏度配置、自動旋轉、無限循環,核心代碼 < 100 行,無額外依賴(除 jQuery),可直接集成至電商商品頁、房產看房、汽車展示等場景。

copyright © 萬盛學電腦網 all rights reserved