Rendering implemented in an Angular component through Three.js

Currently immersed in developing a dynamically generated three.js component within Angular. The statically created Plot3dComponent (via selector) functions flawlessly. However, encountering difficulties in rendering the component dynamically using ComponentFactoryResolver - despite attempts to introduce delays with setTimeout, the rendering remains unsuccessful. The resulting image from the save function displays only a white rectangle matching the intended width and height, akin to the canvas element. Any suggestions or insights?

Here's a snippet of my template for rendering the component:

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

The condensed component class code snippet is as follows:

@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);

The abbreviated Plot3dComponent component code snippet is outlined below:

@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();
    }());
  }
}

Many thanks and cheers!

Edit: Noteworthy issue detected within @angular/material's mat-tab-groups. Experimented with fixed heights but the problem persists.

Answer №1

I've successfully managed to make it work by utilizing both static and dynamic component creation. You can check out a minimal stackblitz I created with a working example. Below is the snippet of the code related to this.

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

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Experiencing a typeerror with the Event attribute

I encountered an issue while trying to target an event. Here is what I attempted: public gotoPage(event: Event): void { const gettest = (event.target as HTMLElement)?.getAttribute('href'); if (href) { const testModule = "valu ...

utilizing Nuxt code in Elixir/Phoenix

Overview In my previous work, I combined frontend development with nuxt and backend support from elixir/phoenix, along with nginx for reverse proxy. Looking to enhance the performance of the system, my goal is now to migrate everything to Elixir/Phoenix. ...

Searching Local JSON Data in Ionic 4 with a Filter Input Bar

My current challenge involves filtering local JSON data in my Ionic project. Despite referencing other resources, I am unable to filter or display filtered items on the ngx-datatable. I suspect the issue may lie either in the filterItems function implement ...

Clear previous loop data in PHP

I have a "show recent" pictures div on my website that I want to refresh every 20 seconds to display a new picture. However, the issue is that my current ajax call refreshes instantly instead of after 20 seconds and it fails to delete the previous data, re ...

What is the proper way to utilize e.key and e.target.value in TypeScript when coding with React?

I'm struggling to get e.key and e.target.value working with the following code: const handleInputKeyPress = (e: React.KeyboardEvent<HTMLInputElement> ) => { if(e.key ==='Enter') { dfTextQuery(e.target.value) } }; Why is & ...

Creating dynamic qtip2 tooltips is an effective way to enhance user interaction on

I am facing an issue where all tooltips work perfectly fine when the page loads, but stop working after data refreshes through ajax. How can I resolve this problem? $(document).ready(function() { // MAKE SURE YOUR SELECTOR MATCHES SOMETHING IN YOUR HT ...

Trouble with Bootstrap Popover's visibility

My current setup involves a popover that is not initializing properly. The code I am using is shown below: HTML: <div data-toggle="popover" data-placement="bottom" data-content="xyz">...</div> JavaScript: $(function () { $('[data-t ...

React code displaying misalignment between label and input

Can you help me align my URL and https:// on the same margin? https://i.sstatic.net/hxkkC.png <div className="card"> <div className="card-body"> <div className="form-group col-12"> <label cla ...

Encountering issues when trying to upload a video to a Facebook page using the Graph

Trying to publish a video to a specific Facebook page using the guidelines provided by Facebook's documentation at this link, but encountering persistent errors. Below is the code snippet: try { let mediaPostParams = new URLSearchParams() ...

Passing a type argument to the custom Toolbar of MUI DataGrid in TypeScript React: A step-by-step guide

Utilizing a personalized Toolbar alongside the Material UI DataGrid, I am transferring a set of props through object syntax: import { DataGrid } from "@mui/x-data-grid"; import InternalToolbar from "../InternalToolbar"; <DataGrid ...

Dynamic value updates using jQuery input type formulas

I need help with a form that has two inputs: The first input allows the user to enter an amount, such as 1000. The second input is read-only and should display the value of the first input plus 1%. For example, if the user types in 1000 in the first fie ...

What is the best way to apply a border-radius to the top of bars in @nivo/bar?

Is it possible to apply a border radius to the tops of each stack in a stacked responsive bar created from the Nivo library, without affecting the bottom? Currently, the responsive bar's border radius applies to both the top and bottom. Thank you! ...

invoking a function within an object in Typescript

export class MockedDataService { constructor(private Session: SessionService) {} private getMockedResponse(name:string){ return ""; // placeholder for the response data, will be a promise } public mocked:{ products:{ ...

The compatibility between `webpack-streams` and `@types/webpack`

I encountered an issue with my gulpfile while building it with TypeScript. Everything was working fine until I included @types/webpack-stream. Suddenly, I started getting a series of errors that looked quite ugly: node_modules/@types/webpack-stream/index.d ...

What is causing the error message "Error: Cannot update active font: 'Fira Sans' is not included in the font list" in react-font-picker?

For my project, I have implemented a font picker component in the following manner: <FontPicker apiKey={process.env.REACT_APP_GOOGLE_API_KEY} activeFontFamily={activeFontFamilyMobile} ...

What is the proper way to utilize a class with conditional export within the Angular app.module?

This query marks the initiation of the narrative for those seeking a deeper understanding. In an attempt to incorporate this class into app.module: import { Injectable } from '@angular/core'; import { KeycloakService } from 'keycloak-angul ...

Initiate a click event on an anchor element with the reference of "a href"

I'm currently facing an issue with clicking a href element on my HTML website. The click event doesn't seem to be triggered. CODE: HTML CODE: <div class="button" id="info" ></div> <ul id="game-options"> <li><a ...

Is it possible to modify a prop in a functional component?

I am working on a functional component that has the following structure: export const Navbarr = ({items}) => { const [user, error] = useAuthState(auth); const [cartItems, setCartItems] = React.useState(0); const fetchUserCartItems = async() =&g ...

Combine Rest API with JSON into BPMN for React or Angular 8 along with TypeScript compatibility

Looking for an angular or react BPMN library that supports TypeScript and REST API services without needing to parse XML. I've searched extensively but can't find a BPMN library with JSON service. I need to create a workflow similar to this us ...

Restrict the number of rows in a CSS grid

Hello there, I am in the process of creating an image gallery using CSS grid. Specifically, my goal is to initially show just one row of images and then allow users to click a "Show more" button to reveal additional images. You can see my progress here: ...