如何将solidworks的模型嵌入到网页中运行并且进行交互?

作者站长头像
站长
· 阅读数 4

有一个solidworks装配模型,希望能够嵌入到网页中,当点击某个部位的时候,能够触发函数事件,并且修改该部位的颜色。

回复
1个回答
avatar
test
2024-06-25

把SolidWorks 转成→ GLTF/OBJ格式:

<!DOCTYPE html>
<html>
<head>
  <title>SolidWorks Model Viewer</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
  <script src="https://threejs.org/examples/js/loaders/GLTFLoader.js"></script>
  <style>
    #model-container {
      width: 100%;
      height: 100vh;
      background-color: #eee;
    }
  </style>
</head>
<body>
  <div id="model-container"></div>
  <script>
    
    const scene = new THREE.Scene();
    const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
    const renderer = new THREE.WebGLRenderer();
    renderer.setSize(window.innerWidth, window.innerHeight);
    document.getElementById('model-container').appendChild(renderer.domElement);

    // 加光源
    const light = new THREE.PointLight(0xffffff, 1, 1000);
    light.position.set(0, 0, 10);
    scene.add(light);

    // 加载模型
    const loader = new THREE.GLTFLoader();
    loader.load('path/to/your/model.gltf', function (gltf) {
      const model = gltf.scene;
      scene.add(model);
      camera.position.z = 5;
    });

    // 交互
    const raycaster = new THREE.Raycaster();
    const mouse = new THREE.Vector2();

    function onMouseClick(event) {
      mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
      mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;

      raycaster.setFromCamera(mouse, camera);

      const intersects = raycaster.intersectObjects(scene.children, true);

      if (intersects.length > 0) {
        const object = intersects[0].object;
        object.material.color.set(0xff0000);  // 改变颜色为红色
      }
    }

    window.addEventListener('click', onMouseClick, false);

   
    function animate() {
      requestAnimationFrame(animate);
      renderer.render(scene, camera);
    }

    animate();
  </script>
</body>
</html>
回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容