gpt4 book ai didi

javascript - 动态 Angular 组件中的 Three.js 渲染

转载 作者:搜寻专家 更新时间:2023-10-30 21:57:51 25 4
gpt4 key购买 nike

目前正在 Angular 中动态创建 three.js 组件。静态(通过选择器)创建的 Plot3dComponent 完美运行。但是当通过 ComponentFactoryResolver 动态创建它时,组件不会渲染任何东西。还尝试使用 setTimeout 添加一些延迟,但我无法让它呈现任何内容。 save 函数的图像输出只是一个具有所需宽度和高度的白色矩形,就像 canvas 元素一样。你有什么想法吗?

在我的模板中渲染组件

<ng-container #plot3dref></ng-container>

缩小后的组件类如下所示

@ViewChild('plot3dref', {read: ViewContainerRef}) plot3dref: ViewContainerRef;

save(geometry: Geometry) {
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(Plot3dComponent);
const componentRef = this.plot3dref.createComponent(componentFactory);
const instance = (<Plot3dComponent>componentRef.instance);

instance.geometry = geometry;
instance.materials = this.materials;
instance.selectedBlock = -1;

console.log(instance.save());
}, 100);

缩小后的 Plot3dComponent 看起来像这样

@Component({
selector: 'app-plot-3d',
template: '<canvas #canvas></canvas>',
styles: [`:host { width: 100%; } canvas { width: 100%; }`],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class Plot3dComponent implements OnInit, AfterViewInit, OnDestroy {
@ViewChild('canvas') private canvasRef: ElementRef;
@Input() geometry: Geometry;
@Input() selectedBlock: number;
@Input() materials: Material[];
[...]

ngOnInit() { this.render = this.render.bind(this); }
save() { return this.canvasRef.nativeElement.toDataURL(); }

ngAfterViewInit() {
this.startRendering();
}

private startRendering() {
this.renderer = new THREE.WebGLRenderer({
canvas: this.canvas,
antialias: true,
preserveDrawingBuffer: true
});

const component: Plot3dComponent = this;

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

谢谢,干杯!

编辑:这个问题似乎也出现在@angular/materialmat-tab-groups 中。还在那里测试了固定高度。

最佳答案

实际上它可以同时处理静态和动态组件创建。创建了一个最小的 stackblitz与工作示例。这是相关的代码片段。

export class DynamicComponent {
@ViewChild('canvas') private canvasRef: ElementRef;
[...]

ngOnInit() {
const renderer = new WebGLRenderer();
renderer.setSize(200, 150);
this.canvasRef.nativeElement.append(renderer.domElement);
[...]
}

关于javascript - 动态 Angular 组件中的 Three.js 渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51455862/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com