Skip to content

266. 3D 产品展示网站(二)

Published:

上节实现了颜色切换:

2026-01-24 19.59.07.gif

2026-01-24 19.59.37.gif

2026-01-24 20.00.08.gif

这节我们加上滚动控制颜色切换。

我们在 App.jsx 加一下 html 部分:

image.png

<div className='section section1'>
    <h1>缤纷色彩,自由选择</h1>
</div>
<div className='section section2'>
</div>
<div className='section section3'>
</div>

加一下样式,改下 App.css:

* {
  margin: 0;
}

#content {
  position: fixed;
  top: 0;
  left: 0;
}

.section {
  height: 100vh;
  text-align: center;
  transition: background-color 0.5s ease;
}

.section h1 {
  font-size: 50px;
  margin-bottom: 0px;
  font-weight: 300;
}

设置下 3D 场景的背景透明:

image.png

image.png

这样也就不需要设置透明度了。

看下效果:

2026-01-24 20.47.03.gif

然后我们再做一下滚动的时候切换坐垫颜色。

image.png

image.png

去掉 OrbitControls,滚动的时候修改坐垫颜色。

let curPageNo = 0;

// 定义每个 section 对应的坐垫颜色
const cushionColors = [
    'lightgreen',  // section1 - 浅绿色(默认)
    '#f5576c',     // section2 - 粉红色
    '#00f2fe',     // section3 - 青色
    '#38f9d7',     // section4 - 青绿色
    '#fee140',     // section5 - 黄色
];
// const controls = new OrbitControls(camera, renderer.domElement);

// 滚动监听,根据滚动位置切换坐垫颜色
window.addEventListener('scroll', () => {
    const pageNo = Math.round(window.scrollY / window.innerHeight);

    if(pageNo !== curPageNo) {
        curPageNo = pageNo;

        // 根据 name 查找坐垫并切换颜色
        scene.traverse((child) => {
            if (child.isMesh && child.name === 'cushion_Cushion_0') {
                if (cushionColors[curPageNo]) {
                    child.material.color.set(cushionColors[curPageNo]);
                }
            }
        });
    }
});

2026-01-24 21.01.16.gif

这样,颜色切换就完成了。

看下网上这个:

2026-01-24 15.16.54.gif

切换颜色这部分是一样的。

案例代码上传了小册仓库

总结

这节我们把滚动控制颜色切换的功能完成了。

下节继续来做更多的产品展示的交互。

评论