three Path 使用小结

126 阅读2分钟

Path 是什么有什么作用

  • Path 是一个创建线条的API
  • 能通过这个API创建线条

Path 有几个方法分别有什么用

  • currentPoint 获取当前moveTo 点位,如果有添加新点位默认为新点位
  • absarc 创建弧形线,结束点为弧形的结束点,坐标中心点相对于canvas
  • absellipse 创建椭圆,坐标中心点相对于canvas
  • arc 创建弧形线,坐标中心点相对于currentPoint
  • bezierCurveTo 创建一条贝塞尔曲线
  • ellipse 创建椭圆,坐标中心点相对于currentPoint
  • lineTo 连接线到指定点
  • moveTo 移动 currentPoint 位置
  • quadraticCurveTo 创建一条二次曲线
  • setFromPoints 将一组点位设置到线条中为直线
  • splineThru 将一组点位设置到线条中并且为曲线

使用示例


<template>
    <div id="parkingLot" ref="parkingLot">
    </div>
</template>
<script setup>
import { ref, onMounted, onUnmounted } from "vue";
import * as THREE from 'three';
import * as Interpolations from 'three/src/extras/core/Interpolations.js';
const parkingLot = ref();

onMounted(() => {
    const DOMEl = parkingLot.value;
    // 获取 DOMEl 的宽度和高度,以设置渲染器的大小。
    const width = DOMEl.clientWidth;
    const height = DOMEl.clientHeight;


    const renderer = new THREE.WebGLRenderer();
    renderer.setSize( width, height );
    DOMEl.appendChild( renderer.domElement );
    const scene = new THREE.Scene();
    const camera = new THREE.PerspectiveCamera( 45, width / height, 1, 2000 );
    camera.position.set( 0, 300, 800 );
    camera.lookAt( 0, 0, 0 );

    const path = new THREE.Path();
    path.moveTo(0, 0);  // 起点
    path.absarc(50, 50, 20, 0, Math.PI, false);
    path.lineTo(10, 10);  // 直线
    path.quadraticCurveTo(20, 15, 30, 10);  // 二次贝塞尔曲线
    path.bezierCurveTo(40, 5, 50, 5, 60, 10);  // 三次贝塞尔曲线// 在绝对位置 (70, 50) 处绘制一个半径为 20 的圆弧
    path.absarc(70, 50, 20, 0, Math.PI, false);
    path.splineThru([
        new THREE.Vector2(10, 10),
        new THREE.Vector2(20, 20),
        new THREE.Vector2(30, 10),
        new THREE.Vector2(40, 20)
    ])
    path.lineTo(70, 0);  // 结束线段
    const points = path.getPoints();

    const geometry = new THREE.BufferGeometry().setFromPoints( points );
    const material = new THREE.LineBasicMaterial( { color: 0xffffff } );

    const line = new THREE.Line( geometry, material );
    scene.add( line );

    // 创建光源
    const light = new THREE.DirectionalLight(0x0000ff, 10);
    light.position.set(10, 10, 10);
    light.castShadow = true;
    scene.add(light);


    renderer.render(scene, camera);

});
</script>
<style lang="scss" scoped="scoped">

    #parkingLot {
        width: 940px;
        height: 940px;
        border: 1px solid #ccc;
        margin: 30px auto;
    }

</style>