【问题标题】:How do I draw <div> elements on top of a three.js canvas with a transparent background?如何在具有透明背景的 three.js 画布上绘制 <div> 元素?
【发布时间】:2018-08-29 12:18:52
【问题描述】:

我正在阅读this answer,但提出的方法纯粹是理论上的。在我的 HTML5 代码中,我尝试过这样的事情:

<div id='gameCanvas'>
    <div id="insideText">First trial</div>
</div>

我在 CSS 中写了这个:

#insideText{
    background-color: transparent;
}

当谈到 HTML/CSS 时,我是个新手,所以我可能会犯一些简单的错误,但这样我的画布上方会出现一条黑线,并且文本出现在该黑线中。我希望文本出现在没有这条黑线的画布上,我还想知道如何在画布的不同区域放置一些文本(我的画布不是全屏的)。

编辑: 如果我将&lt;div&gt; 放在画布元素之外,它确实会以透明背景显示,但始终作为独立于画布的元素。

【问题讨论】:

  • 您的具体要求是什么?您的页面上有画布,并且您希望在这些画布上放置一个 div,覆盖所有画布区域?所以用户可以直接点击/与画布交互。对吗?
  • 我需要在画布区域中绘制 div 以显示基本 UI。我还希望它们具有透明背景,以便 3D 场景在它们背后可见。

标签: html css


【解决方案1】:

您的问题并非特定于三个或画布。这只是一个基本的 HTML/CSS 问题,我敢肯定在这个网站上已经回答了 1000 次,但由于搜索很糟糕,我会再次回答,并将其留给更有耐心的人作为骗子关闭

要使 2 个或更多元素重叠,您通常需要一个父元素。该元素必须具有 css position: relative;position:absolute;。这使它成为其子代的锚点/起源/基础。注意:&lt;body&gt; 已经这样标记了。

然后对于所有孩子,您可以使用position:absolute 并使用lefttoprightbottom 设置他们的位置

例子

const ctx = document.querySelector('canvas').getContext('2d');
ctx.fillStyle = 'yellow';
ctx.fillRect(0, 0, 300, 150);
ctx.fillStyle = 'red';
ctx.arc(150, 75, 125, 0, Math.PI * 2, true);
ctx.fill();
<h1>Some text</h1>

<div style="position: relative; display: inline-block;">
  <canvas></canvas>
  <div style="position: absolute; left: 1em; top: 1em;">foo</div>
  <div style="position: absolute; right: 1em; bottom: 1em;">bar</div>
</div>

注意:display: inline-block; 是为了使外部元素适合内容,而不是拉伸到其父元素(在本例中为主体)的宽度。有 100 多种其他方法可以设置元素的大小。

请注意,默认情况下元素是透明的,因此无需将背景颜色设置为透明,除非您在其他地方将其设置为不透明

const renderer = new THREE.WebGLRenderer();
document.querySelector('#gameCanvas').appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.add(
 new THREE.Mesh(
   new THREE.SphereGeometry(1), 
   new THREE.MeshBasicMaterial({color:'red'})
 )
);
scene.background = new THREE.Color('yellow');
const camera = new THREE.PerspectiveCamera(45, 2, .1, 10);
camera.position.z = 2;
renderer.render(scene, camera);
#gameCanvas {
  position: relative;
}
#insideText {
  position: absolute;
  left: 20px;
  top: 20px;
}
<h1>some text</h1>
<div id='gameCanvas'>
    <div id="insideText">First trial</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/95/three.min.js"></script>

【讨论】:

  • 文本的绝对定位是关键!
猜你喜欢
  • 2019-04-16
  • 2016-09-24
  • 1970-01-01
  • 2010-11-04
  • 1970-01-01
  • 2012-12-18
  • 1970-01-01
  • 1970-01-01
  • 2012-05-07
相关资源
最近更新 更多