无法附加我用threejs创建的div

时间:2018-08-26 16:03:27

标签: javascript

因此,我创建了一个在特定位置创建div的函数。然后我加载threejs。这是一个Webgl引擎,应该运行一个旋转的多维数据集。现在,我希望threejs在我创建的div中运行。但是,当我检查“容器”时,它输出为空。好像无法识别div在那。我在做什么错??

//Make div for canvas
function AdDiv(divname)
{
    //make a div that will be used for the canvas
    var iDiv = document.createElement('div');
    iDiv.id = 'placedCanvas';
    iDiv.className = 'placedCanvas';
    document.getElementById(divname).appendChild(iDiv);
    console.log("canvas created");
}


function loadScript(url, callback)
{
    // Adding the script tag to the head as suggested before
    var head = document.getElementsByTagName('head')[0];
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = url;
    // Then bind the event to the callback function.
    // There are several events for cross browser compatibility.
    script.onreadystatechange = callback;
    script.onload = callback;
    // Fire the loading
    head.appendChild(script);
}

var myPrettyCode = function()
{
    var scene, camera, renderer, container;
    var WIDTH  = window.innerWidth;
    var HEIGHT = window.innerHeight;
    var SPEED = 0.01;

    function init() 
    {
        scene = new THREE.Scene();
        initCube();
        initCamera();
        initRenderer();

        //document.body.appendChild(renderer.domElement);

        var container = document.getElementById('placedCanvas');
        container.appendChild(renderer.domElement); //This doesn't work??
        console.log(container); //Container seems to output null
    }

    function initCamera() 
    {
        camera = new THREE.PerspectiveCamera(70, WIDTH / HEIGHT, 1, 10);
        camera.position.set(0, 3.5, 5);
        camera.lookAt(scene.position);
    }

    function initRenderer() 
    {
        renderer = new THREE.WebGLRenderer({ antialias: true });
        renderer.setSize(200, 200);
    }

    function initCube() 
    {
        cube = new THREE.Mesh(new THREE.CubeGeometry(2, 2, 2), new THREE.MeshNormalMaterial());
        scene.add(cube);
    }

    function rotateCube() 
    {
        cube.rotation.x -= SPEED * 2;
        cube.rotation.y -= SPEED;
        cube.rotation.z -= SPEED * 3;
    }

    function render() 
    {
        requestAnimationFrame(render);
        rotateCube();
        renderer.render(scene, camera);
    }

    init();
    render();
};

loadScript("https://pixelvaria.com/wp-content/themes/pixelvaria/js/three.js",myPrettyCode);

这是我执行功能的html页面

<div id="canvasdiv"></div>
<script type="text/javascript" src="https://pixelvaria.com/wp-content/themes/pixelvaria/js/modelscript.js" async></script>
        <script>
            function codeAddress()
            {
                AdDiv("canvasdiv");
            }
            window.onload = codeAddress;
        </script>

1 个答案:

答案 0 :(得分:0)

我正在加载javascript异步。我删除了此代码,代码开始工作了!