【问题标题】:Vue.js, Three.js, how to change CSS style element in animation loopVue.js,Three.js,如何在动画循环中更改 CSS 样式元素
【发布时间】:2021-12-06 18:49:46
【问题描述】:

我正在尝试使用 Vue.js 转换我的 Three.js 项目

我有一个 Three.js 场景,其中包含一个 3D 模型和该模型上的 HTML 兴趣点。

这些点必须保持固定在模型上并保持面向相机。

这是我的代码的一部分,它工作正常:

<body>
        <div class="point point-1">
            <div class="point__label">1</div>
            <div class="point__text">
                Lorem ipsum, dolor sit amet consectetur adipisicing elit
            </div>
        </div>
</body>
setPointsOfInterest() {
    this.points = [
        {
            position: new THREE.Vector3(0, 10, 0.2),
            element: document.getElementsByClassName('point-1'),
        },
    ];
}

animate() {
    for (const point of this.points) {
        // Get 2D screen position
        const screenPosition = point.position.clone();
        screenPosition.project(this.camera);

        // Transform points
        const x = screenPosition.x * window.innerWidth * 0.5;
        const y = -screenPosition.y * window.innerHeight * 0.5;
        point.element.style.transform = `translateX(${x}px) translateY(${y}px)`;
    }
    
    this.renderer.render(this.scene, this.camera);
    requestAnimationFrame(this.animate.bind(this));
}

使用Vue.js,我用THREE.Vector3设置点的位置并没有改变,它只是使用CSS样式,为什么?

我怎样才能像这里一样在我的动画循环中更改我的 CSS 元素?

【问题讨论】:

    标签: javascript html css vue.js three.js


    【解决方案1】:

    Vue.js 强烈建议您不要手动选择它构建的 DOM 元素,因为您会很快遇到冲突的命令。此外,它根据自己的组件生命周期构建和销毁元素,因此在您尝试选择 "point-1" 时它们可能不存在。

    考虑到这一点,您不应该使用 documents.getElementsByClassName() 来选择和操作元素,而应该尝试使用 Vue 自己的 Template Refs system. 建立后,您应该能够像这样更新其 CSS 位置:

    this.$refs.point1.style.transform = `translateX(${x}px) translateY(${y}px)`;
    

    【讨论】:

      猜你喜欢
      • 2022-08-12
      • 2021-12-31
      • 2015-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-07
      • 2022-08-19
      • 1970-01-01
      相关资源
      最近更新 更多