Three.js 3D魔方 完整可运行代码原生Three.js实现可旋转、拖拽视角、鼠标拖动魔方3D魔方直接复制HTML打开即用!DOCTYPEhtmlhtmllangzh-CNheadmetacharsetUTF-8titleThree.js 3D魔方/titlestyle*{margin:0;padding:0;box-sizing:border-box;}body{overflow:hidden;background:#111;}canvas{display:block;}/style/headbodyscriptsrchttps://cdn.jsdelivr.net/npm/three0.158.0/build/three.min.js/scriptscriptsrchttps://cdn.jsdelivr.net/npm/three0.158.0/examples/js/controls/OrbitControls.js/scriptscript// 初始化场景constscenenewTHREE.Scene();scene.backgroundnewTHREE.Color(0x1a1a2e);// 相机constcameranewTHREE.PerspectiveCamera(60,window.innerWidth/window.innerHeight,0.1,1000);camera.position.set(8,8,12);// 渲染器constrenderernewTHREE.WebGLRenderer({antialias:true});renderer.setSize(window.innerWidth,window.innerHeight);document.body.appendChild(renderer.domElement);// 轨道控制器 拖拽旋转视角constcontrolsnewTHREE.OrbitControls(camera,renderer.domElement);controls.enableDampingtrue;// 灯光constambientnewTHREE.AmbientLight(0xffffff,0.6);scene.add(ambient);constdirLightnewTHREE.DirectionalLight(0xffffff,0.8);dirLight.position.set(10,20,15);scene.add(dirLight);// 魔方颜色constcolors[0xff0000,// 红0x00ff00,// 绿0x0000ff,// 蓝0xffff00,// 黄0xffa500,// 橙0xffffff// 白];// 创建单个小方块functioncreateCube(x,y,z){constgeometrynewTHREE.BoxGeometry(1,1,1);constmaterialscolors.map(cnewTHREE.MeshLambertMaterial({color:c}));constcubenewTHREE.Mesh(geometry,materials);cube.position.set(x,y,z);returncube;}// 魔方整体分组construbikGroupnewTHREE.Group();constoffset1.05;// 生成3*3*3魔方for(letx-1;x1;x){for(lety-1;y1;y){for(letz-1;z1;z){rubikGroup.add(createCube(x*offset,y*offset,z*offset));}}}scene.add(rubikGroup);// 窗口适配window.addEventListener(resize,(){camera.aspectwindow.innerWidth/window.innerHeight;camera.updateProjectionMatrix();renderer.setSize(window.innerWidth,window.innerHeight);});// 自动缓慢旋转魔方functionanimate(){requestAnimationFrame(animate);rubikGroup.rotation.y0.003;controls.update();renderer.render(scene,camera);}animate();/script/body/html功能说明视角操控鼠标左键拖拽旋转视角、滚轮缩放、右键平移自动旋转魔方匀速Y轴自转标准六色上下左右前后标准魔方配色高清抗锯齿画面顺滑无锯齿全屏自适应自动适配浏览器窗口大小进阶可扩展功能实现单层旋转左右层、上下层转动加入打乱魔方、一键复原逻辑增加按键控制魔方转动添加光影质感、边框黑线加入触屏适配手机端可玩