【问题标题】:How to draw a line with the mouse on a 3D surface in threejs如何在threejs中用鼠标在3D表面上画一条线
【发布时间】:2021-05-20 15:09:15
【问题描述】:

我一直在寻找一个示例,说明如何在 Threejs 中的场景内的 3D 表面上用鼠标绘制一条线以实现以下图像,但找不到这个具体的示例,希望有人能提供一个如何通过使用鼠标并单击开始,拖动,然后使用鼠标向上获取结束位置来执行此操作的示例。然后使用 3D 空间中的这些位置来绘制线条。

【问题讨论】:

  • 有效问题,但请说明。线应该由二维坐标定义吗?还是应该成为three.js 场景的一部分?例如这里stackoverflow.com/questions/55278137/… 你将看到如何在three.js 画布上渲染2D 矩形。
  • 这条线应该沿着网格表面从鼠标向下绘制到鼠标向上点。所以起点和终点都在 x 和 z 轴上,就像您将棋子拖到棋盘上的新位置一样。

标签: three.js


【解决方案1】:

您需要在 mousedown 和 mousemove 中将点投射到平面上,您应该在 mousemove 中而不是在 mouseup 中执行此操作,因为鼠标可能会在您的平面之外释放,因此请跟踪鼠标在此期间最后的位置拖动选项是 imo 的最佳方法。

renderer.domElement.addEventListener('mousedown', e => {
  if (e.button === 0) {
    isMouseDown = true;
    const x = (e.clientX / ctx.renderer.domElement.clientWidth) * 2 - 1;
    const y = -(e.clientY / ctx.renderer.domElement.clientHeight) * 2 + 1;
    
    rayCaster.setFromCamera({ x, y }, ctx.camera);
    const intersections = rayCaster.intersectObject(plane);
    if (intersections && intersections.length) {
      hitPoint.copy(intersections[0].point);
      lineGeometry.setFromPoints([ hitPoint, intersections[0].point ]);
      }
  }
});
Sample Pen

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多