【发布时间】:2015-10-23 19:33:51
【问题描述】:
我有一个显示 3D 图形的简单 WebGL 代码。它工作得很好,但我想为宽度设置一个不同于 100% 的值;即我想把 webGL 动画放在一个小盒子里。
在我的代码下面;我试图将 WebGL 放入带有 CSS“高度”和“宽度”的 500px 框中,但它不起作用:动画仍然占用 100% 的宽度:
<!DOCTYPE html>
<html lang="en">
<head>
<title>three.js webgl - trackball controls</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<style>
body {
color: #000;
font-family:Monospace;
font-size:13px;
text-align:center;
font-weight: bold;
background-color: #fff;
margin: 0px;
overflow: hidden;
}
.container {
width: 500px;
height: 500px;
}
</style>
</head>
<body>
<center><div id="container"></div></center>
<script src="three.js/build/three.min.js"></script>
<script src="three.js/examples/js/controls/TrackballControls.js"></script>
<script src="three.js/examples/js/Detector.js"></script>
<script src="three.js/examples/js/libs/stats.min.js"></script>
<script>
if ( ! Detector.webgl ) Detector.addGetWebGLMessage();
var container, stats;
var camera, controls, scene, renderer;
var cross;
init();
animate();
function init() {
...
}
function onWindowResize() {
...
}
function animate() {
requestAnimationFrame( animate );
controls.update();
// For displaying
render();
}
function render() {
renderer.render( scene, camera );
stats.update();
}
</script>
</body>
</html>
如何规避这个问题?
谢谢
更新 1:
好的,对于类 ID 混淆感到抱歉。
关于 div 容器,我在WebGL 代码中使用appenChild 添加renderer domElement。
使用以下代码:
<html lang="en">
<head>
<title>three.js webgl - trackball controls</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<style>
body {
color: #000;
font-family:Monospace;
font-size:13px;
text-align:center;
font-weight: bold;
background-color: #fff;
margin: 0px;
overflow: hidden;
}
#container {
width: 300px;
height: 300px;
margin-left: auto;
margin-right: auto;
}
</style>
</head>
<body>
<div id="container"></div>
<script src="three.js/build/three.min.js"></script>
<script src="three.js/examples/js/controls/TrackballControls.js"></script>
<script src="three.js/examples/js/Detector.js"></script>
<script src="three.js/examples/js/libs/stats.min.js"></script>
<script>
if ( ! Detector.webgl ) Detector.addGetWebGLMessage();
...
</script>
</body>
</html>
我没有得到带有 WebGL 动画的居中框。 WebGL 窗口像这样向右移动(宽度设置为 300 像素),但它不像我想的那样居中。
PS:margin-left:auto 和 margin-right:auto 似乎不适用于居中。
谢谢。
【问题讨论】:
-
init和onWindowResize是与画布大小最相关的函数。请提供这些。
标签: javascript html css three.js