【问题标题】:Three.js rendering in dynamic Angular componentThree.js 在动态 Angular 组件中渲染
【发布时间】:2018-12-29 13:15:04
【问题描述】:

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

用于渲染组件的模板

<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 中似乎也出现了这个问题。还在那里测试了固定高度。

【问题讨论】:

  • 尝试向主机添加height: 100%
  • 不工作,尝试height: 100% 在:host、canvas 和两者上。

标签: javascript angular typescript three.js rendering


【解决方案1】:

实际上,它可以同时用于静态和动态组件创建。使用工作示例创建了一个最小的stackblitz。这是相关的代码sn-p。

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

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

【讨论】:

    猜你喜欢
    • 2018-02-06
    • 2023-03-14
    • 2021-06-14
    • 2019-08-18
    • 1970-01-01
    • 2020-01-31
    • 1970-01-01
    • 1970-01-01
    • 2014-12-18
    相关资源
    最近更新 更多