jor*_*ume 3 javascript canvas three.js
这实际上是我已经解决的问题,但出于好奇,我想知道是否有人可以解释为什么会出现这种情况?
这是我的html:
<!DOCTYPE html>
<html>
<head>
<script src="three.min.js"></script>
<script src="OrbitControls.js"></script>
<script type="text/javascript" src="webgl.js"></script>
</head>
<body style="margin: 0;">
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
和我的JS:
var scene, camera, renderer;
init();
animate();
function init(){
scene = new THREE.Scene();
var width = window.innerWidth, height = window.innerHeight;
renderer = new THREE.WebGLRenderer({antialias:true});
renderer.setSize(width, height);
document.body.appendChild(renderer.domElement);
}
Run Code Online (Sandbox Code Playgroud)
这不起作用,我得到“Uncaught TypeError: Cannot read property 'appendChild' of null ”
但是当我将 webgl.js 脚本移动到正文时,它会正确渲染画布元素。
为什么会出现这种情况?为什么我的脚本需要位于正文中才能附加 dom 元素?渲染器对象在我的控制台中返回画布,那么问题是什么?
小智 5
当脚本在 head 内部被调用时,body 还不存在。您可以通过调用console.log(document.body)
头部和身体来看到这一点。你会发现那document.body
是null
因为身体还没有被创造出来。