Javascript 即使存在对象属性,Typescript也无法访问它们

Javascript 即使存在对象属性,Typescript也无法访问它们,javascript,typescript,properties,Javascript,Typescript,Properties,尽管对象中存在属性,但我在访问属性时遇到了问题,但typescript告诉我它们不存在。我创建了一个粒子对象,其中包含形状的几何体和材质。我需要能够访问粒子的几何体顶点,但尝试时typescript会抛出一个匹配。例如,this.particles.geometry.vertices.length应该返回我的顶点的长度,但typescript说,当顶点实际存在时,它在几何体中不存在 我的问题发生在加载图像、创建顶点之后,然后我需要将它们移动到目标索引,但它表示this.particles.geo

尽管对象中存在属性,但我在访问属性时遇到了问题,但typescript告诉我它们不存在。我创建了一个粒子对象,其中包含形状的几何体和材质。我需要能够访问粒子的几何体顶点,但尝试时typescript会抛出一个匹配。例如,
this.particles.geometry.vertices.length
应该返回我的顶点的长度,但typescript说,当顶点实际存在时,它在几何体中不存在

我的问题发生在加载图像、创建顶点之后,然后我需要将它们移动到目标索引,但它表示this.particles.geometry.vertices不存在

这是包含几何体的粒子对象,几何体内部是一个属性,即包含所有顶点的顶点,但我无法以显示的方式访问它们。

这是我的全部源代码。drawImage方法将正确绘制所有顶点,并将顶点对象推入我的几何体对象。完成后,我将几何体添加到粒子中,效果很好,我将其添加到场景中,并显示所有顶点。问题是我无法访问顶点来操纵它们。所以我的粒子对象、drawImage和包含for循环的渲染方法就是所有这些发生的地方。在我的渲染方法中,它只是说类型“Geometry | buffer Geometry”上不存在(TS)属性“顶点”。它确实存在,我通过图像显示,我的粒子对象是一个点对象,它包含我的几何体,几何体内部有一个属性,它包含我所有的顶点,称为顶点

import { Component, AfterViewInit, ElementRef, Input, ViewChild, HostListener} from '@angular/core';
import { TweenLite } from 'gsap';
import * as THREE from 'three';
declare const require: (moduleId: string) => any;
var OrbitControls = require('three-orbit-controls')(THREE);

@Component({
    selector: 'shared-background-scene',
    templateUrl: './backgroundScene.component.html',
    styleUrls: ['./backgroundScene.component.scss']
})

export class BackgroundSceneComponent {

    public scene: THREE.Scene;
    private renderer: THREE.WebGLRenderer;
    private camera: THREE.PerspectiveCamera;
    private cameraTarget: THREE.Vector3;
    public controls: THREE.OrbitControls;

    public fieldOfView: number = 60;
    public nearClippingPane: number = 1;
    public farClippingPane: number = 1100;

    @ViewChild('canvas')
    private canvasRef: ElementRef;

    public particles: THREE.Points;
    public imageData: any;
    public geometry = new THREE.Geometry();
    public material = new THREE.PointsMaterial({
                size: 3,
                color: 0x313742,
                sizeAttenuation: false
    });
    public loadImage() {
        //load texture, which is the image, and then get the imagedata, and draw image.
        var texture = new THREE.TextureLoader().load("assets/img/example-clouds.png", () => { console.log(texture); this.imageData = this.getImageData(texture.image); this.drawImage(); this.startRendering(); })
    }

    public getImageData(image: any) {
        console.log(image);
        // Create canvas for the image
        let canvas = document.createElement("canvas");
        canvas.width = image.width;
        canvas.height = image.width;

        // Make sure context is 2d
        let context = canvas.getContext("2d");
        context!.drawImage(image, 0, 0);

        //return the context to be saved to the imageData.
        return context!.getImageData(0, 0, image.width, image.height);
    }

    public drawImage() {

        // Create vertices to draw the image.
        for (var y = 0, y2 = this.imageData.height; y < y2; y += 2) {
            for (var x = 0, x2 = this.imageData.width; x < x2; x += 2) {
                if (this.imageData.data[(x * 4 + y * 4 * this.imageData.width) + 3] > 128) {

                    let vertex:any = new THREE.Vector3();
                    vertex.x = Math.random() * 1000 - 500;
                    vertex.y = Math.random() * 1000 - 500;
                    vertex.z = -Math.random() * 500;

                    vertex.destination = {
                        x: x - this.imageData.width / 2,
                        y: -y + this.imageData.height / 2,
                        z: 0
                    };

                    vertex.speed = Math.random() / 200 + 0.015;

                    this.geometry.vertices.push(vertex);
                }
            }
        }

        console.log(this.geometry);
        this.particles = new THREE.Points(this.geometry, this.material);
        this.scene.add(this.particles);
        console.log(this.particles);
        requestAnimationFrame(this.render);
    }

    constructor() {
        this.render = this.render.bind(this);
    }

    private get canvas(): HTMLCanvasElement {
        return this.canvasRef.nativeElement;
    }

    private createScene() {
        this.scene = new THREE.Scene();
    }

    private createCamera() {
        let aspectRatio = this.getAspectRatio();
        this.camera = new THREE.PerspectiveCamera(
            this.fieldOfView,
            aspectRatio,
            this.nearClippingPane,
            this.farClippingPane
        );

        // Set position and look at
        this.camera.position.x = 10;
        this.camera.position.y = 10;
        this.camera.position.z = 100;
    }

    private getAspectRatio(): number {
        let height = this.canvas.clientHeight;
        if (height === 0) {
            return 0;
        }
        return this.canvas.clientWidth / this.canvas.clientHeight;
    }

    private startRendering() {
        this.renderer = new THREE.WebGLRenderer({
            canvas: this.canvas,
            antialias: true
        });
        this.renderer.setPixelRatio(devicePixelRatio);
        this.renderer.setSize(this.canvas.clientWidth, this.canvas.clientHeight);

        this.renderer.shadowMap.enabled = true;
        this.renderer.shadowMap.type = THREE.PCFSoftShadowMap;
        this.renderer.setClearColor(0xffffff, 1);
        this.renderer.autoClear = true;

        let component: BackgroundSceneComponent = this;

        (function render() {
            requestAnimationFrame(render);
            component.render();
        }());
    }

    public render() {
        this.renderer.render(this.scene, this.camera);

        for (var i = 0, j = this.particles.geometry.vertices; i < j; i++) {
            var particle = this.particles.geometry.vertices[i];
            particle.x += (particle.destination.x - particle.x) * particle.speed;
            particle.y += (particle.destination.y - particle.y) * particle.speed;
            particle.z += (particle.destination.z - particle.z) * particle.speed;
        }
        this.particles.geometry.verticesneedupdate = true;
    }

    public addControls() {
        this.controls = new OrbitControls(this.camera);
        this.controls.rotateSpeed = 1.0;
        this.controls.zoomSpeed = 1.2;
        this.controls.addEventListener('change', this.render);

    }

    private loadCubeModel() {
        var geometry = new THREE.BoxGeometry(1, 1, 1);
        var material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
        var cube = new THREE.Mesh(geometry, material);
        this.scene.add(cube);
    }

    /* Events */
   private onResize(event: Event) {
        this.canvas.style.width = "100%";
        this.canvas.style.height = "100vh";
        //console.log("onResize: " + this.canvas.clientWidth + ", " + this.canvas.clientHeight);

        this.camera.aspect = this.getAspectRatio();
        this.camera.updateProjectionMatrix();
        this.renderer.setSize(this.canvas.clientWidth, this.canvas.clientHeight);
        this.render();
    }

    /* LIFECYCLE */
   ngAfterViewInit() {
        this.createScene();
        this.createCamera();
        this.loadImage(); // rendering starts here
        this.loadCubeModel();
        this.addControls();
    }
}
从'@angular/core'导入{Component,AfterViewInit,ElementRef,Input,ViewChild,HostListener};
从“gsap”导入{TweenLite};
从“三”中导入*作为三;
declare const require:(moduleId:string)=>any;
var轨道控制=需要(“三轨道控制”)(三);
@组成部分({
选择器:“共享背景场景”,
templateUrl:'./backgroundScene.component.html',
样式URL:['./backgroundScene.component.scss']
})
导出类背景场景组件{
公共场景:三、场景;
私有渲染器:3.WebGLRenderer;
私人摄像机:3.透视摄像机;
私人摄像机目标:3.Vector3;
公共控制:三种控制;
公共视野:数字=60;
公共近剪报页:编号=1;
公共剪报机:数量=1100;
@ViewChild('画布')
私人画布参考:ElementRef;
公共粒子:三点;
公共图像数据:任何;
公共几何体=新的三个。几何体();
公共材料=新的三点材料({
尺寸:3,
颜色:0x313742,
sizeAttenuation:false
});
公共加载映像(){
//加载纹理,即图像,然后获取图像数据,并绘制图像。
var texture=new THREE.TextureLoader().load(“assets/img/example clouds.png”,()=>{console.log(texture);this.imageData=this.getImageData(texture.image);this.drawImage();this.startRendering();})
}
公共getImageData(图像:任意){
console.log(图像);
//为图像创建画布
让canvas=document.createElement(“canvas”);
canvas.width=image.width;
canvas.height=image.width;
//确保上下文是二维的
让context=canvas.getContext(“2d”);
上下文图像(图像,0,0);
//返回要保存到imageData的上下文。
返回context!.getImageData(0,0,image.width,image.height);
}
公众形象({
//创建顶点以绘制图像。
对于(变量y=0,y2=this.imageData.height;y128){
让顶点:any=新的3.Vector3();
vertex.x=Math.random()*1000-500;
vertex.y=Math.random()*1000-500;
vertex.z=-Math.random()*500;
vertex.destination={
x:x-this.imageData.width/2,
y:-y+this.imageData.height/2,
z:0
};
vertex.speed=Math.random()/200+0.015;
这个.geometry.vertex.push(顶点);
}
}
}
console.log(this.geometry);
this.particles=新的三个点(this.geometry,this.material);
this.scene.add(this.particles);
console.log(this.particles);
requestAnimationFrame(this.render);
}
构造函数(){
this.render=this.render.bind(this);
}
private get canvas():HTMLCanvasElement{
返回此.canvasRef.nativeElement;
}
私有createScene(){
this.scene=新的三个.scene();
}
私有createCamera(){
让aspectRatio=this.getAspectRatio();
this.camera=新的3.perspective相机(
这个视野,
aspectRatio,
这个,靠近剪报机,
这是剪报纸
);
//设置位置并查看
这个.camera.position.x=10;
这个.camera.position.y=10;
这个.camera.position.z=100;
}
私有getAspectRatio():编号{
让高度=this.canvas.clientHeight;
如果(高度==0){
返回0;
}
返回this.canvas.clientWidth/this.canvas.clientHeight;
}
私人startRendering(){
this.renderer=new THREE.WebGLRenderer({
canvas:this.canvas,
反别名:对
});
this.renderer.setPixelRatio(devicePixelRatio);
this.renderer.setSize(this.canvas.clientWidth,this.canvas.clientHeig
import { Component, AfterViewInit, ElementRef, Input, ViewChild, HostListener} from '@angular/core';
import { TweenLite } from 'gsap';
import * as THREE from 'three';
declare const require: (moduleId: string) => any;
var OrbitControls = require('three-orbit-controls')(THREE);

@Component({
    selector: 'shared-background-scene',
    templateUrl: './backgroundScene.component.html',
    styleUrls: ['./backgroundScene.component.scss']
})

export class BackgroundSceneComponent {

    public scene: THREE.Scene;
    private renderer: THREE.WebGLRenderer;
    private camera: THREE.PerspectiveCamera;
    private cameraTarget: THREE.Vector3;
    public controls: THREE.OrbitControls;

    public fieldOfView: number = 60;
    public nearClippingPane: number = 1;
    public farClippingPane: number = 1100;

    @ViewChild('canvas')
    private canvasRef: ElementRef;

    public particles:any = THREE.Points;
    public imageData: any;
    public geometry = new THREE.Geometry();
    public material = new THREE.PointsMaterial({
                size: 3,
                color: 0x313742,
                sizeAttenuation: false
    });
    public loadImage() {
        //load texture, which is the image, and then get the imagedata, and draw image.
        var texture = new THREE.TextureLoader().load("assets/img/transparentMap.png", () => { console.log(texture); this.imageData = this.getImageData(texture.image); this.drawImage(); this.startRendering(); })
    }

    public getImageData(image: any) {
        console.log(image);
        // Create canvas for the image
        let canvas = document.createElement("canvas");
        canvas.width = image.width;
        canvas.height = image.width;

        // Make sure context is 2d
        let context = canvas.getContext("2d");
        context!.drawImage(image, 0, 0);

        //return the context to be saved to the imageData.
        return context!.getImageData(0, 0, image.width, image.height);
    }

    public drawImage() {

        // Create vertices to draw the image.
        for (var y = 0, y2 = this.imageData.height; y < y2; y += 2) {
            for (var x = 0, x2 = this.imageData.width; x < x2; x += 2) {
                if (this.imageData.data[(x * 4 + y * 4 * this.imageData.width) + 3] > 128) {

                    let vertex:any = new THREE.Vector3();
                    vertex.x = Math.random() * 1000 - 500;
                    vertex.y = Math.random() * 1000 - 500;
                    vertex.z = -Math.random() * 500;

                    vertex.destination = {
                        x: x - this.imageData.width / 2,
                        y: -y + this.imageData.height / 2,
                        z: 0
                    };

                    vertex.speed = Math.random() / 200 + 0.015;

                    this.geometry.vertices.push(vertex);
                }
            }
        }
        this.particles = new THREE.Points(this.geometry, this.material);
        this.scene.add(this.particles);

        requestAnimationFrame(this.render);
    }

    constructor() {
        this.render = this.render.bind(this);
    }

    private get canvas(): HTMLCanvasElement {
        return this.canvasRef.nativeElement;
    }

    private createScene() {
        this.scene = new THREE.Scene();
    }

    private createCamera() {
        let aspectRatio = this.getAspectRatio();
        this.camera = new THREE.PerspectiveCamera(
            this.fieldOfView,
            aspectRatio,
            this.nearClippingPane,
            this.farClippingPane
        );

        // Set position and look at
        this.camera.position.x = 10;
        this.camera.position.y = 10;
        this.camera.position.z = 100;
    }

    private getAspectRatio(): number {
        let height = this.canvas.clientHeight;
        if (height === 0) {
            return 0;
        }
        return this.canvas.clientWidth / this.canvas.clientHeight;
    }

    private startRendering() {
        this.renderer = new THREE.WebGLRenderer({
            canvas: this.canvas,
            antialias: true
        });
        this.renderer.setPixelRatio(devicePixelRatio);
        this.renderer.setSize(this.canvas.clientWidth, this.canvas.clientHeight);

        this.renderer.shadowMap.enabled = true;
        this.renderer.shadowMap.type = THREE.PCFSoftShadowMap;
        this.renderer.setClearColor(0xffffff, 1);
        this.renderer.autoClear = true;

        let component: BackgroundSceneComponent = this;

        (function render() {
            requestAnimationFrame(render);
            component.render();
        }());
    }

    public render() {
        this.renderer.render(this.scene, this.camera);

        // Draw image to screen
        for (var i = 0, j = this.particles.geometry.vertices.length; i < j; i++) {
            var particle:any = this.particles.geometry.vertices[i];
            particle.x += (particle.destination.x - particle.x) * particle.speed;
            particle.y += (particle.destination.y - particle.y) * particle.speed;
            particle.z += (particle.destination.z - particle.z) * particle.speed;
        }
        this.particles.geometry.verticesNeedUpdate = true;
    }

    public addControls() {
        this.controls = new OrbitControls(this.camera);
        this.controls.rotateSpeed = 1.0;
        this.controls.zoomSpeed = 1.2;
        this.controls.addEventListener('change', this.render);

    }

    private loadCubeModel() {
        var geometry = new THREE.BoxGeometry(1, 1, 1);
        var material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
        var cube = new THREE.Mesh(geometry, material);
        this.scene.add(cube);
    }

    /* Events */
   private onResize(event: Event) {
        this.canvas.style.width = "100%";
        this.canvas.style.height = "100vh";
        //console.log("onResize: " + this.canvas.clientWidth + ", " + this.canvas.clientHeight);

        this.camera.aspect = this.getAspectRatio();
        this.camera.updateProjectionMatrix();
        this.renderer.setSize(this.canvas.clientWidth, this.canvas.clientHeight);
        this.render();
    }

    /* LIFECYCLE */
   ngAfterViewInit() {
        this.createScene();
        this.createCamera();
        this.loadImage(); // rendering starts here
        this.loadCubeModel();
        this.addControls();
    }
}
const geometry = this.particles.geometry as Geometry