You need to enable JavaScript to run this app. Three.js实现移动端设备倾斜/陀螺仪控制相机运动的方法
优惠活动
大模型
产品
解决方案
定价
更多

Three.js实现移动端设备倾斜/陀螺仪控制相机运动的方法

实现方案

核心思路

  • 无需引入threeVR等额外库,直接使用原生DeviceOrientationEventAPI实现陀螺仪控制,和现有相机逻辑完全兼容
  • 复用原有渲染流程中的mouseX、mouseY变量做中间值,仅需将陀螺仪的倾斜角度映射到这两个变量上,无需修改原有相机的缓动、跟随逻辑
  • 做端侧适配:桌面端保留原有鼠标移动控制逻辑,移动端移除原触摸控制,替换为陀螺仪控制,同时兼容iOS 13+的陀螺仪权限校验规则

关键修改说明

  • 移除原有touchmove事件绑定,避免移动端触摸操作和陀螺仪控制冲突
  • 陀螺仪参数映射规则:
    • beta:设备前后倾斜角度(绕X轴旋转,范围-180°~180°),对应原有上下方向的控制维度
    • gamma:设备左右倾斜角度(绕Y轴旋转,范围-90°~90°),对应原有左右方向的控制维度
    • 限制有效倾斜范围为±45°,避免设备大幅倾斜导致相机过度偏移
  • iOS权限处理:iOS 13及以上系统必须在用户主动触发的事件中申请陀螺仪权限,添加临时权限申请按钮完成授权流程

可直接替换的修改后代码

const nearDist = 0.1;
const farDist = 10000;

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(
    55,
    window.innerWidth / window.innerHeight,
    nearDist,
    farDist
);
camera.position.x = farDist * -2;
camera.position.z = 500;

const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setClearColor("#e8a82b"); 
renderer.setPixelRatio(window.devicePixelRatio); 
renderer.setSize(window.innerWidth, window.innerHeight);
document.querySelector("#canvas-wrapper").appendChild(renderer.domElement);

// Object
const cubeSize = 300;
const geometry = new THREE.IcosahedronGeometry(cubeSize, 0 );
const material = new THREE.MeshNormalMaterial({roughness: 1});
const group = new THREE.Group();
for (let i = 0; i < 260; i++) {
    const mesh = new THREE.Mesh(geometry, material);
    const dist = farDist / 3;
    const distDouble = dist * 2;
    const tau = 2 * Math.PI;

    mesh.position.x = Math.random() * distDouble - dist;
    mesh.position.y = Math.random() * distDouble - dist;
    mesh.position.z = Math.random() * distDouble - dist;
    mesh.rotation.x = Math.random() * tau;
    mesh.rotation.y = Math.random() * tau;
    mesh.rotation.z = Math.random() * tau;

    mesh.matrixAutoUpdate = false;
    mesh.updateMatrix();

    group.add(mesh);
}
scene.add(group);
// Typo
const loader = new THREE.FontLoader();
const textMesh = new THREE.Mesh();
const createTypo = font => {
    const word = "be creative";
    const typoProperties = {
        font: font,
        size: cubeSize,
        height: cubeSize / 2,
        curveSegments: 16
    };
    const text = new THREE.TextGeometry(word, typoProperties);
    textMesh.geometry = text;
    textMesh.material = material;
    textMesh.position.x = cubeSize * -2;
    textMesh.position.z = cubeSize * -1;
    scene.add(textMesh);
};
// 字体文件需放置在项目可访问的本地路径下
loader.load("helvetiker_regular.typeface.json", createTypo);

// 控制逻辑(核心修改部分)
const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
let mouseX = 0;
let mouseY = 0;
const mouseFX = {
    windowHalfX: window.innerWidth / 2,
    windowHalfY: window.innerHeight / 2,
    coordinates: function(coordX, coordY) {
        mouseX = (coordX - mouseFX.windowHalfX) * 2;
        mouseY = (coordY - mouseFX.windowHalfY) * 2;
    },
    onMouseMove: function(e) {
        mouseFX.coordinates(e.clientX, e.clientY);
    }
};
// 仅桌面端绑定鼠标移动事件
if (!isMobile) {
    document.addEventListener("mousemove", mouseFX.onMouseMove, false);
}

// 移动端陀螺仪控制逻辑
if (isMobile) {
    // iOS 13+ 权限适配
    if (typeof DeviceOrientationEvent !== 'undefined' && typeof DeviceOrientationEvent.requestPermission === 'function') {
        const authBtn = document.createElement('button');
        authBtn.innerText = '开启陀螺仪控制';
        authBtn.style.cssText = 'position:fixed;top:20px;left:50%;transform:translateX(-50%);z-index:999;padding:12px 24px;border:none;border-radius:8px;background:#ffffff;box-shadow:0 2px 8px rgba(0,0,0,0.15);';
        authBtn.onclick = async () => {
            const permissionState = await DeviceOrientationEvent.requestPermission();
            if (permissionState === 'granted') {
                window.addEventListener('deviceorientation', handleOrientationChange, false);
                authBtn.remove();
            }
        };
        document.body.appendChild(authBtn);
    } else {
        // 非iOS 13+的移动端直接监听陀螺仪事件
        window.addEventListener('deviceorientation', handleOrientationChange, false);
    }

    // 倾斜角度映射,可根据使用习惯调整tiltRange数值控制灵敏度
    function handleOrientationChange(e) {
        if (e.beta === null || e.gamma === null) return;
        const tiltRange = 45; // 有效倾斜角度阈值,数值越小控制越灵敏
        // 左右倾斜映射到X轴控制值
        const targetX = Math.max(Math.min(e.gamma, tiltRange), -tiltRange) / tiltRange * window.innerWidth;
        // 前后倾斜映射到Y轴控制值,匹配原有逻辑的正负方向
        const targetY = Math.max(Math.min(e.beta, tiltRange), -tiltRange) / tiltRange * window.innerHeight;
        mouseX = targetX;
        mouseY = targetY * -1;
    }
}

// Render
const render = () => {
    requestAnimationFrame(render);

    // Camera animation 原有逻辑无需修改
    camera.position.x += (mouseX - camera.position.x) * 0.05;
    camera.position.y += (mouseY * -1 - camera.position.y) * 0.05;
    camera.lookAt(scene.position);

    const t = Date.now() * 0.001;
    const rx = Math.sin(t * 0.6) * 0.5;
    const ry = Math.sin(t * 0.3) * 0.5;
    const rz = Math.sin(t * 0.2) * 0.5;
    group.rotation.x = rx;
    group.rotation.y = ry;
    group.rotation.z = rz;
    textMesh.rotation.x = rx;
    textMesh.rotation.y = ry;
    textMesh.rotation.z = rx;

    renderer.render(scene, camera);
};
render();


const resizeCanvas = () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
};
window.addEventListener("resize", resizeCanvas, false);

调试提示

  • 如果陀螺仪控制方向反了,可调整handleOrientationChange函数中targetX、targetY的正负号即可
  • 控制灵敏度可通过修改tiltRange参数调整,数值越小同样倾斜角度对应的相机偏移量越大
  • 桌面端访问时不会出现权限按钮,鼠标控制逻辑和原有逻辑完全一致

内容的提问来源于stack exchange,提问作者Martin Sprušanský

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.23 17:06:05