Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0613· OpenAIAi2 WildChat-4.8M (AI2)

в чем проблема? ошибка: Uncaught (in promise) TypeError: Cannot read properties of…

  1. User

    в чем проблема? ошибка: Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'getPixelRatio') в коде: import * as THREE from 'three'; import Stats from 'three/addons/libs/stats.module.js'; import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js'; import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'; import { RectAreaLightHelper } from 'three/addons/helpers/RectAreaLightHelper.js'; import { RectAreaLightUniformsLib } from 'three/addons/lights/RectAreaLightUniformsLib.js'; import { gsap } from "gsap"; // import { FontLoader } from 'three/addons/loaders/FontLoader.js'; import {EffectComposer} from 'three/addons/postprocessing/EffectComposer.js'; import {RenderPass} from 'three/addons/postprocessing/RenderPass.js'; import { UnrealBloomPass } from 'three/examples/jsm/postprocessing/UnrealBloomPass.js'

    async function loadShaderFile(url) { const response = await fetch(url); const shaderCode = await response.text(); return shaderCode; }

    async function main() {

    const loader = new GLTFLoader();
    loader.load(
        'CUBE R1 a.glb',
        async (gltf) => {
            const cube = gltf.scene;
            let anim = gltf.animations;
            console.log(anim)
            let container, stats, clock;
            
            let camera, scene, renderer;
            let rectLight1,rectLight2;
            
            const segments = 3000;
            const r = 3;
            let t = 0;
            
            init();
            RectAreaLightUniformsLib.init();
            scene.add(cube);
            cube.castShadow = true;			
            cube.receiveShadow = true; 
            // cube.scale.set(1.0,1.0,1.0);
            // cube.position.set(0,-0.3,0);
    
            const light = new THREE.AmbientLight( 0x404040 ); 
            scene.add( light );
            
        
        async function init() {
            
            container = document.getElementById( 'container' );
            
            camera = new THREE.PerspectiveCamera( 20, window.innerWidth / window.innerHeight, 0.01, 4000 );
            camera.position.z = 9;
    
            const renderScene = new RenderPass(scene,camera);
            const composer = new EffectComposer(renderer);
            composer.addPass(renderScene);     
            const bloomPass = new UnrealBloomPass(
                new THREE.Vector2(window.innerWidth,window.innerHeight),
                1.6,
                0.1,
                0.1
            )
            composer.addPass(bloomPass);
    
    
            scene = new THREE.Scene();
            
            const shaderCode = await loadShaderFile('frag.glsl');
            const texture2 = new THREE.TextureLoader().load('logoGradient4.png');
            let uTime = 0;
            rectLight1 = new THREE.RectAreaLight( 0xffffff, 20, 4, 4 );
            scene.add( rectLight1 );
            rectLight1.castShadow = true;
            rectLight1.position.set( 2, -1, -2 );
            rectLight1.rotation.set(0,Math.PI/2,0);
            // scene.add( new RectAreaLightHelper( rectLight1 ) );
            rectLight2 = new THREE.RectAreaLight( 0xffffff, 20, 1, 1 );
            scene.add( rectLight2 );
            rectLight2.castShadow = true;
            rectLight2.position.set( -2, 0, -2 );
            rectLight2.rotation.set(Math.PI/5,-Math.PI/1.5,Math.PI/1.5);
            renderer = new THREE.WebGLRenderer( { antialias: true } );
            renderer.setPixelRatio( window.devicePixelRatio );
            renderer.setSize( window.innerWidth, window.innerHeight );
            renderer.useLegacyLights = false;
            container.appendChild( renderer.domElement );
            
            stats = new Stats();
            container.appendChild( stats.dom );
            cube.scale.set(0.16,0.16,0.16);
            
            window.addEventListener( 'resize', onWindowResize );
            const controls = new OrbitControls(camera, renderer.domElement);
            controls.enableDamping = true;
            controls.dampingFactor = 0.05;
            scene.add(controls.target);
    
            const mixer = new THREE.AnimationMixer( cube );
            const clips = cube.animations;
            // Play all animations
            clips.forEach( function ( clip ) {
                mixer.clipAction( clip ).play();
            } );
            
            
            const cubeUp = cube.clone();
            const cubeDown = cube.clone();
            scene.add(cubeUp);
            cubeUp.castShadow = true;			
            cubeUp.receiveShadow = true; 
            cubeUp.position.y = 0.32;
            scene.add(cubeDown);
            cubeDown.castShadow = true;			
            cubeDown.receiveShadow = true; 
            cubeDown.position.y = -0.32;
            
            gsap.to(cube.rotation,{
                y: Math.PI,
                duration: 2.4,
                repeat: -1,
                delay: 0.5,
                repeatDelay: 3,
                ease: "power1.inOut"
            })
            gsap.to(cubeUp.rotation,{
                y: Math.PI,
                duration: 2.4,
                repeat: -1,
                delay: 1.2,
                repeatDelay: 2,
                ease: "power1.inOut"
            })
            gsap.to(cubeDown.rotation,{
                y: Math.PI,
                duration: 2.4,
                repeat: -1,
                delay: 3.5,
                repeatDelay: 4,
                ease: "power1.inOut"
            })
    
    
            const groupCube = new THREE.Group();
            groupCube.add( cube );
            groupCube.add( cubeUp );
            groupCube.add( cubeDown );
            scene.add(groupCube);
            function animate(animations) {
                requestAnimationFrame( animate );
                for (let i = 0; i < animations.length; i++) {
                    // animations[i].play();
                }
                mixer.update( uTime );
                controls.update();
                uTime += 0.01;
                groupCube.rotation.set(uTime,uTime,uTime);
                render();
                stats.update();
            }
            animate(gltf.animations);
        }
        
        function onWindowResize() {
            camera.aspect = window.innerWidth / window.innerHeight;
            camera.updateProjectionMatrix();
            renderer.setSize( window.innerWidth, window.innerHeight );
        }
        
        function render() {
            composer.render();
            // renderer.render( scene, camera );
        }
        
    }    
    );    
    
    

    }; main()

  2. Assistant

    Одной из возможных проблем является то, что в вашем коде отсутствует инициализация переменных renderer и composer. Вы пытаетесь использовать эти переменные внутри функции init(), но они не определены в этом контексте. Как результат, возникает ошибка "Cannot read properties of undefined (reading 'getPixelRatio')".

    Чтобы решить эту проблему, вам нужно объявить и инициализировать эти переменные перед использованием их в функции init(). Например, вы можете добавить следующие строки кода перед вызовом функции init():

    renderer = new THREE.WebGLRenderer({ antialias: true });
    composer = new EffectComposer(renderer);
    

    Также, возможна другая проблема, связанная с загрузкой шейдерного файла. У вас есть функция loadShaderFile(url), которая асинхронно загружает текст шейдерного кода с помощью fetch. Возможно, во время выполнения функции происходит ошибка при загрузке файла, и возвращается undefined. Проверьте, что файл frag.glsl находится в корректном месте и доступен для загрузки.

    Наконец, возможно, у вас отсутствуют некоторые зависимости, которые должны быть установлены для использования THREE.js. Проверьте, что все зависимости установлены и подключены корректно.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.