在父div中居中使用three.js renderer.domElement(canvas)

时间:2015-06-18 15:03:04

标签: css three.js

我很难理解如何使用' style' html div中的threejs渲染器的输出。

例如,这是一个简单的场景:

jsFiddle

HTML:

<div id="myPlanet"></div>    

css:

body {
background : #000;
padding : 50px;
margin : 0;
}
#myPlanet {
width : 400px;
min-height: 400px;
margin : auto;
}

以及js的摘录:

// The WIDTH of the scene to render
var __WIDTH__  = 400,

// The HEIGHT ot the scene to render
__HEIGHT__ = 400,
// We need to define the size of the renderer
renderer.setSize(__WIDTH__, __HEIGHT__);

// Let's attach our rendering zone to our page
document.getElementById("myPlanet").appendChild(renderer.domElement);

如果元素宽度(以css为单位)与渲染器宽度完全匹配,则输出在结果页面中完全居中。但是,当div&#39; myplanet&#39;扩展(宽度)超出渲染器的400px(即将css规则更改为600px宽度或100%)jsthree输出然后只是位于元素的左侧。

这怎么能集中?在css中你必须创建一个特殊的规则案例(例如像#myplanet img或者其他东西)然后你可以设置样式吗?我试过把&#39; margin:0 auto;&#39;在myplanet规则中,它仍然不会使输出居中

1 个答案:

答案 0 :(得分:2)

默认情况下,<canvas>元素被视为内联对象,类似于<img>元素。这使得它可以使用float:left;float:right;属性来混合文本和图像。我在父div和透明的红色背景中添加了一些文本以表现出这种行为。

inline canvas

在这种情况下,您有两种选择。

1)为canvas元素设置margin: auto 同时指定画布应被浏览器的页面呈现引擎视为块元素。

#canvas{
    display: block;
    margin: 0 auto;
}

你明白了:

disaply:block, margin:auto

2)为父div设置text-align: center

或者,您可以指定内联元素的垂直对齐属性。

#myPlanet{
    text-align: center;
   /* vertical-align: middle; */
}

我强烈推荐第一个选项。

text-align:center