1. ホーム
  2. js

three.jsは車の3Dライブビュー(カラーインタラクション)を実装しています。

2022-03-03 17:45:24
<パス

質問元です。
    師匠とやりとりして、卒業設計に使おうと思い、three.jsの勉強を始めました。半月以上かけて基礎から学び、ようやくスタートできたので、その結果をご紹介します。

コードデモです。
htmlセクション

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>3D (color interaction)</title>
    <script src="js/jquery-3.3.1.min.js"></script>
    <script src="three.js/build/three.js"></script>
    <script src="js/OrbitControls.js"></script>
    <script src="three.js/examples/js/loaders/GLTFLoader.js"></script>
</head>
<body>
<div id="contorl">
    <input class="color" type="color">
</div>
<script src="js/model.js"></script>
</body>
</html>



model.css

body {
    margin: 0 ;
	padding: 0 ;
    overflow: hidden; /* overflow hidden */
}
#contorl{
    position: absolute;
    width: 15%;
    height: 20%;
    right: 20px;
    top: 20px;
    background-color: white;
}
.select{
    font-family: "Microsoft elegant black";
    background: rgba(0,0,0,0);
    width: 70%;
    height: 30%;
    font-size: 12px;
    color: black;
    text-align: center;
    border: 1px #1a1a1a solid;
    border-radius: 5px;
}
.select > option{
    color: black;
    background: #fff;
    line-height: 20px;
}
.select:focus{
    border: 2px #0000ff solid;
    box-shadow: 0 0 15px 1px #DDDDDD;
}
.select > option:hover{
    background: #EBCCD1;
}
.color{
    border: none;
    outline: none;
}
::-webkit-color-swatch-wrapper{background-color:#ffffff;}
::-webkit-color-swatch{position: relative;}


model.js (ここが肝心なところ)

 let scene, camera, renderer, controls, guiControls;
    // let stats = initStats();

    /* Scene */
    function initScene() {

        Scene = new THREE;
        var skySphereGeometry = new THREE.SphereGeometry( 500, 30, 100 );
        var texture = new THREE.TextureLoader().load("images/timg.jpg");
        var skySphereMaterial = new THREE.MeshBasicMaterial( { map:texture, side: THREE.DoubleSide } );
        var skySphere = new THREE.Mesh( skySphereGeometry, skySphereMaterial );
        scene.add(skySphere);

    }

    /* Camera */
    function initCamera() {

        camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 10000);
        camera.position.set(70, 50, 100);
        camera.lookAt(new THREE.Vector3(0, 0, 0));

    }

    /* Renderer */
    function initRender() {

        renderer = new THREE.WebGLRenderer({antialias: true});
        renderer.setSize(window.innerWidth, window.innerHeight);
        renderer.setClearColor(0xffffff);
        renderer.shadowMap.enabled = true;
        document.body.appendChild(renderer.domElement);

    }

    /* Light */
    function initLight() {
        // var axes = new THREE.AxesHelper(20);
        // scene.add(axes);

        var planeGeometry = new THREE.PlaneGeometry(200,200,100,1);
        var texture = new THREE.TextureLoader().load("images/5.png");
        var planeMaterial = new THREE.MeshLambertMaterial({map:texture});
        Mesh(planeGeometry, planeMaterial). var plane = new THREE;
        // plane.rotation.x = -0.5*Math.PI;
        // plane.name = 'plane';
        // plane.position.set(0,0,0);
        // plane.receiveShadow = true;
        // scene.add(plane);

        var ambiColor = "#ffffff";
        AmbientLight(ambiColor); // set the color
        sc

    /* Controllers */
    function initControls() {
        controls = new THREE.OrbitControls(camera, renderer.domElement);
		// Remove this function if the animate method is used
		// controls.addEventListener( 'change', render );
		// Make the animation damping or rotating when used in a loop Meaning whether it has inertia or not
		controls.enableDamping = true;
		// dynamic damping factor is the mouse dragging and rotation sensitivity
		controls.dampingFactor = 0.95;
		//whether it can be zoomed
		controls.enableZoom = true;
		// whether to automatically rotate
		// controls.autoRotate = true;
		// set the farthest distance of the camera from the origin
		controls.minDistance = 70;
		// set the farthest distance of the camera from the origin
		controls.maxDistance = 250;
		//whether to enable right-click dragging
		controls.enablePan = false;
		// Set the focus coordinates
		// controls.target = new THREE.
    Vector3() }

    /* Debug the plugin */
    function initGui() {

        guiControls = new function () {
            this.rotationSpeed = 0;
        };
    }

    /* Content in the scene */

    function initContent() {

        // Load the model in glTF format
        let loader = new THREE.GLTFLoader();/* instantiate loader */
        loader.load('. /example/11/scene.gltf',function (obj) {
            obj.scene.name = 'zp';
			var car = obj.scene;
			console.log(car.children[0].children[0].children[0]);
            scene.add(car);
        },function (xhr) {

            console.log( ( xhr.loaded / xhr.total * 100 ) + '% loaded' );

        },function (error) {
			console.log(error)
            // console.log('load error!'+error.getWebGLErrorMessage());
        })

    }

    /* performance plugin */
    function initStats() {

        let stats = new Stats();
        document.body.appendChild(stats.domElement);
        return stats;

    }

    /* Triggered by a window change */
    function onWindowResize() {

        camera.aspect = window.innerWidth / window.innerHeight;
        camera.updateProjectionMatrix();
        renderer.setSize(window.innerWidth, window.innerHeight);

    }

    /* Data update */
    function update() {

        // stats.update();

    }

    /* Initialize */
    function init() {
        initScene();
        initCamera();
        initRender();
        initLight();
        initControls();
        initContent();
        initGui();
        /* Listen to events */
        window.addEventListener('resize', onWindowResize, false);
    }

    /* Render in a loop */
    function animate() {
        requestAnimationFrame(animate);
        renderer.render(scene, camera);
        update();

    }

    /* Initial loading */
    (function () {
        console.log("three init start... ");

        init();
        animate();

        console.log("three init send... ");
    })();


    window.onload = function() {
        var color = document.getElementsByClassName('color')[0];
        color.onchange = function(e){
            var change_thing = scene.getObjectByName('confirm');
            colors = change_thing.material.color;
            var hex = document.getElementsByClassName('color')[0].value;
            var c = hex_rgb(hex);
            colors.r = c[0];
            colors.g = c[1];
            colors.b = c[2];
        };
        function hex_rgb(hex){
            var r = parseInt(hex[1]+ hex[2],16)/255;
            var g = parseInt(hex[3]+ hex[4],16)/255;
            var b = parseInt(hex[5]+ hex[6],16)/255;
            return [r, g, b];
        }
        function get_hex(x){
            var e = parseInt(x*255).toString(16);
            var z = e;
            if (e === 0){
                z = '00';
            }
            if (e.length === 1){
                z = '0' + e;
            }
            return z;
        }
        function rgb_hex(r, g, b){
            var result = '#' + get_hex(r) + get_hex(g) + get_hex(b);
            return result;
        }

        var raycaster = new THREE;
        var mouse = new THREE.Vector3(

ページが表示されます。
[外部画像ダンプに失敗しました(img-JJ42GWf9-1563801784739) ( https://raw.githubusercontent.com/zpwyl/images/master/TIM图片20190405161647.png )]
[外部イメージのダンプに失敗しました (img-gkN7jNo9-1563801784741) ( https://raw.githubusercontent.com/zpwyl/images/master/TIM图片20190405161710.png )]
私はストレートな人間で、アートワークの才能はあまりなく、最終的な結果は満足のいくものではありません。私の地味な作品をご覧になった方の中から、何かご指摘をいただければと思いますし、私の過去の時間のまとめでもあります。

学習過程で遭遇した問題点と学習サイトを紹介します。
他の種類の3Dファイルの読み込み。
OBJです。

var mtlLoader = new THREE.MTLoader();
mtlLoader.setPath('exapmle/4/');
mtlLoader.load('car.mtl', function(materials) {
	console.log(materials);
	materials.preload();
	var objLoader = new THREE.OBJLoader();
	objLoader.setMaterials(materials);
	objLoader.setPath('exapmle/4/');
	objLoader.load('car.obj', function(object) {
		console.log(object, 'obj');
		object.position.y = 0;
		object.rotation.y = 0.5;
		object.scale.set(0.05, 0.05, 0.05);
		console.log(object);
		scene.add(object);
     }, onProgress, onError);
 });


VTKです。

var loader = new THREE.VTKLoader();
loader.addEventListener( 'load', function ( event ) {
	var geometry = event.content;
	var mesh = new THREE.Mesh( geometry, material );
	mesh.position.setY( - 0.09 );
	scene.add( mesh );
	} );
loader.load( "models/vtk/bunny.vtk" );


WebGL 中国語            http://www.hewebgl.com/
Three.js公式ドキュメント        https://threejs.org/
3Dモデルダウンロード                https://sketchfab.com