You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中组件向类传参:如何将颜色选择器值传入POI类设置圆柱颜色

实现颜色选择器参数传递到Three.js圆柱体材质

步骤1:完善颜色选择器组件的变量定义

首先在object-settings.component.ts中添加color1的公共属性,满足双向绑定需求:

// object-settings.component.ts
public color1: string = "#FF00FF"; // 初始值与圆柱体默认颜色保持一致

步骤2:选择合适的组件间通信方式

根据组件层级关系,选择对应的传递方式:

场景A:object-settings是poiComponent的父组件

  • 在poiComponentClass.ts中添加输入属性:
// poiComponentClass.ts
import { Input } from '@angular/core';

@Input() cylinderColor: string = "#FF00FF"; // 初始默认值
  • 在父组件模板(包含poiComponent的模板)中,将color1绑定到输入属性:
<poi-component [cylinderColor]="color1"></poi-component>

场景B:组件无直接父子关系(兄弟/跨模块)

创建共享服务传递颜色值:

  1. 新建颜色共享服务:
// color-sharing.service.ts
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable({ providedIn: 'root' })
export class ColorSharingService {
  private cylinderColor$ = new BehaviorSubject<string>('#FF00FF');
  public readonly cylinderColor = this.cylinderColor$.asObservable();

  updateColor(color: string): void {
    this.cylinderColor$.next(color);
  }
}
  1. 在object-settings.component.ts中注入服务,监听颜色变化并通知:
// object-settings.component.ts
import { ColorSharingService } from './color-sharing.service';

constructor(private colorService: ColorSharingService) {}

// 利用现有颜色变化事件触发更新
onEventLog(eventType: string, event: any): void {
  if (eventType === 'cpInputChange') {
    this.colorService.updateColor(this.color1);
  }
}
  1. 在poiComponentClass.ts中注入服务,订阅颜色变化:
// poiComponentClass.ts
import { ColorSharingService } from './color-sharing.service';
import { Subscription } from 'rxjs';

private colorSub: Subscription;
private cylinderColor: string = "#FF00FF";

constructor(private colorService: ColorSharingService) {}

ngOnInit(): void {
  this.colorSub = this.colorService.cylinderColor.subscribe(color => {
    this.cylinderColor = color;
    // 若圆柱体已创建,实时更新材质颜色
    if (this.cylinder) {
      this.cylinder.material.color.set(color);
    }
  });
}

ngOnDestroy(): void {
  this.colorSub?.unsubscribe();
}

步骤3:在Three.js中使用传递的颜色

修改poiComponentClass.ts中圆柱体材质的创建代码,替换固定颜色值:

// poiComponentClass.ts
const THREE = this.context.three;
const geometry = new THREE.CylinderGeometry(0.09, 0.09, 5, 5);
geometry.rotateZ(-Math.PI * 0.5);
// 使用传递过来的颜色创建材质
const material = new THREE.MeshBasicMaterial({ color: this.cylinderColor });
this.cylinder = new THREE.Mesh(geometry, material); // 将cylinder设为组件属性,方便后续更新

// 后续原有代码保持不变...
this.sprite.add(this.cylinder);

注意:Three.js的MeshBasicMaterial.color可直接识别十六进制字符串(如#FF00FF),无需额外格式转换,内部会自动处理。

内容的提问来源于stack exchange,提问作者Y Z

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 11:03:20