Three.js:将指定Blob场景嵌入div容器的技术求助
解决方案:将Blob效果嵌入容器并简化功能
我帮你搞定这个Blob效果的容器嵌入问题,同时去掉滚动缩放的功能,这样你就能在它前后自由添加内容,整个页面也能正常滚动啦!下面是具体的修改步骤和完整代码:
1. 调整HTML结构:添加容器
把原来的Blob相关元素(canvas、.blob-wrap这些)放进一个自定义的容器里,同时在容器前后添加示例内容,方便你测试滚动效果:
<p>这是Blob效果之前的内容,可以写任意文本、图片或者其他元素~</p> <!-- 自定义的Blob容器 --> <div class="blob-container"> <canvas id="blob"></canvas> <div class="blob-wrap"> <div class="blob-content"> <h1>BLOB</h1> <p>Static Blob Effect</p> </div> </div> </div> <p>这是Blob效果之后的内容,页面滚动时这些内容会跟着正常上下移动哦!</p>
2. 修改CSS:让Blob适配容器
给容器设置相对定位,让内部的Blob元素能相对于它定位;同时去掉原来全屏相关的样式,确保Blob只在容器范围内显示:
/* 自定义容器样式 */ .blob-container { position: relative; width: 100%; height: 500px; /* 可根据需求调整高度 */ overflow: hidden; /* 防止Blob超出容器 */ margin: 2rem 0; } /* 调整Blob相关元素的定位 */ #blob { position: absolute; top: 0; left: 0; width: 100%; height: 100%; } .blob-wrap { position: absolute; top: 0; left: 0; width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; color: white; text-align: center; pointer-events: none; /* 避免遮挡页面滚动 */ } .blob-content h1 { font-size: 3rem; margin: 0; }
3. 简化JavaScript:移除滚动缩放功能
删掉原来监听滚动事件来缩放Blob的代码,只保留Blob的基础动画逻辑,同时让canvas尺寸适配容器:
const blob = document.getElementById('blob'); const ctx = blob.getContext('2d'); // 让canvas尺寸匹配容器 function resizeCanvas() { const container = document.querySelector('.blob-container'); blob.width = container.offsetWidth; blob.height = container.offsetHeight; } resizeCanvas(); window.addEventListener('resize', resizeCanvas); // Blob核心动画逻辑(保留原有的动态路径效果) let points = []; const pointCount = 12; const radius = Math.min(blob.width, blob.height) / 2; // 初始化随机点 for (let i = 0; i < pointCount; i++) { points.push({ angle: (Math.PI * 2 / pointCount) * i, distance: radius, speed: 0.01 + Math.random() * 0.02 }); } function drawBlob() { ctx.clearRect(0, 0, blob.width, blob.height); ctx.beginPath(); // 绘制Blob路径 points.forEach((point, index) => { point.distance += Math.sin(point.angle) * 5; point.angle += point.speed; const x = blob.width / 2 + Math.cos(point.angle) * point.distance; const y = blob.height / 2 + Math.sin(point.angle) * point.distance; if (index === 0) { ctx.moveTo(x, y); } else { ctx.lineTo(x, y); } }); ctx.closePath(); ctx.fillStyle = '#2563eb'; // 可自定义Blob颜色 ctx.fill(); requestAnimationFrame(drawBlob); } drawBlob(); // 移除滚动缩放逻辑:删掉原代码中监听scroll事件的部分即可
关键修改说明
- 容器定位:给
.blob-container设置position: relative,让内部的绝对定位元素(canvas、.blob-wrap)以容器为基准,不会脱离布局流。 - 尺寸适配:通过
resizeCanvas函数让canvas始终匹配容器宽高,保证Blob充满整个容器且响应窗口大小变化。 - 移除滚动缩放:删掉监听
scroll事件的代码,Blob保持固定大小,不会随页面滚动变形。
这样修改后,你可以随意在.blob-container前后添加任何内容,整个页面滚动时所有元素都会正常跟随,Blob效果也完美嵌在容器里啦!
内容的提问来源于stack exchange,提问作者Rikki Kimo
相关产品推荐
相关产品推荐

