Three.js: Working example of WebGLRenderer using existing canvas/div

Created on 14 Jul 2011  路  6Comments  路  Source: mrdoob/three.js

Hi guys.
Congrats on the wicked library.

Is there an existing working example of https://github.com/mrdoob/three.js/issues/157 "use existing canvas element" fixed by https://github.com/mrdoob/three.js/pull/192 "existing canvas element" ?

There's already a lot of examples but none showing the issue at hand (or i missed it?)
I just started working with this library last week and barely made it possible to show a random object (cube or sphere) which was exported from 3ds max (still some issues with bmw 7 example). But i'd really want to see a working example of the canvas being part of an existing webpage like an online shop.

Would it be possible to have one such example ?

Thank you. Keep up the good work

ps: how can i paste html code here so that is look a bit formatted ?

Question

Most helpful comment

This should work:

var renderer = new THREE.WebGLRenderer( { canvas: my_canvas } );

ps: how can i paste html code here so that is look a bit formatted ?

On the top right of the comment input box you'll find a link that says _GitHub Flavored Markdown_. Click on it ;)

All 6 comments

This should work:

var renderer = new THREE.WebGLRenderer( { canvas: my_canvas } );

ps: how can i paste html code here so that is look a bit formatted ?

On the top right of the comment input box you'll find a link that says _GitHub Flavored Markdown_. Click on it ;)

Good morning.

Wrote this example so that i can try to make an existing canvas work for me. No luck so far. I'm surely missing something but i just can't find out what :(

<!doctype html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>Sample Three.js</title>
        <link rel="stylesheet" type="text/css" href="css/three.css" />
    </head>
    <body>
        <div id="wrapper">
            <div id="header">
                <h2>Threejs test</h2>
            </div>
            <div id="content">
                <div id="container"></div>
            </div>
            <div id="footer">

            </div>
        </div>

        <script type="text/javascript" src="js/Three.js"></script>

        <script type="text/javascript" src="js/Detector.js"></script>
        <script type="text/javascript" src="js/RequestAnimationFrame.js"></script>
        <script type="text/javascript" src="js/Stats.js"></script>
        <script type="text/javascript" src="js/three_test.js"></script>
    </body>
</html>
if(!Detector.webgl) Detector.addGetWebGLMessage();

var container, stats;
var camera, scene, renderer;
var mesh;

var mouseX = 0, mouseY = 0;

var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;

init();
animate();

function init(){
    container = document.getElementById( "container" );

    camera = new THREE.TrackballCamera({

        fov: 60, 
        aspect: window.innerWidth / window.innerHeight,
        near: 1,
        far: 1e3,

        rotateSpeed: 1.5,
        zoomSpeed: 2.5, //below 2.0 zoom feels slow
        panSpeed: 0.2,

        noZoom: false,
        noPan: false,

        staticMoving: false, //false makes moving/rotating the object faster
        dynamicDampingFactor: 0.3,

        keys: [ 65, 83, 68 ]

    });

    camera.position.z = 300;

    scene = new THREE.Scene();

    light = new THREE.AmbientLight(0xffFF00);
    scene.addLight(light);

    var loader = new THREE.JSONLoader();
    loader.load( { model: "models/tea_new.js", callback: function(geometry){createScene(geometry)} } );

    renderer = new THREE.WebGLRenderer( { canvas: container, antialias: true } );
    renderer.setSize( container.style.width, container.style.height );

    container.appendChild( renderer.domElement );

    stats = new Stats();
    stats.domElement.style.position = 'absolute';
    stats.domElement.style.top = '0px';
    container.appendChild(stats.domElement);
}


/**
 * function createScene(geometry) creates the object from the geometry
 * @param geometry the object's geometry
 */
function createScene( geometry ) {

    geometry.materials[0][0].shading = THREE.FlatShading;

    var material = [ new THREE.MeshFaceMaterial(), new THREE.MeshLambertMaterial( { color: 0xffffff, opacity:1, wireframe: false, wireframeLinewidth: 2 } ) ];

    mesh = new THREE.Mesh( geometry, material );
    mesh.position.x = 0;
    mesh.scale.x = mesh.scale.y = mesh.scale.z = 1;
    scene.addObject( mesh );
}


/**
 * function animate() animates the scene
 */
function animate() {
    requestAnimationFrame( animate );

    //render();
    renderer.render( scene, camera );
    stats.update();
}

/**
 * function render() renders the objects on screen and updates camera position
 */
function render() {

    camera.position.x += ( mouseX - camera.position.x ) * 0.05;
    camera.position.y += ( - mouseY - camera.position.y ) * 0.05;

    if ( mesh ) {

        mesh.rotation.x += 0.01;
        mesh.rotation.y += 0.01;
    }

    renderer.render( scene, camera );
}
body {
    background-image: url(../_images/bgsquares.gif);
    background-color: #333;
    color: #000;
    font:75%/1.4 verdana,Helvetica,sans-serif;
}

#wrapper {
    margin: 0 auto; /* auto centers on page */
    height: 100%;
    min-height: 700px;
    margin-top: 10px;
    width: 700px;
}

#container{
    background-color: #555;
    clear: left;
    height: 540px;
    width: 700px;
    float: left;
}

This causes the following in Firebug:

TypeError: ua.getContext is not a function
(undefined="[object Object]")Three.js (line 293)
init()three_test.js (line 49)
Aa=b.stencil!==void 0?b.stencil:!0,xa=...SION)+" | "+j.getParameter(j.VENDOR)+
Three.js (line 293)
j is undefined
error source line: [Break On This Error] " | "+j.getParameter(j.RENDERER)+" | "...ertices=new Float32Array(12);R.faces=

Anyone had a look at this ?

Is it still relevant ?

One quick and maybe important question.

I read >> var renderer = new THREE.WebGLRenderer( { canvas: my_canvas } );

Does that mean that my_canvas is a canvas element or a div element ?
I'm really confused. Maybe it didn't work as expected for me since i was using a div element ...

Any ideas ?

There are two problems here:

renderer = new THREE.WebGLRenderer( { canvas: container, antialias: true } );
renderer.setSize( container.style.width, container.style.height );

container is not a <canvas> element.
containter.style.width and container.style.height are strings such as "200px" on them, and setSize expect just numbers such as 200.

Change these lines to this, and you should be able to go from there:

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

As stated in the guidelines, help requests should be done in stackoverflow. This board is for bugs or feature requests.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

scrubs picture scrubs  路  3Comments

jack-jun picture jack-jun  路  3Comments

filharvey picture filharvey  路  3Comments

seep picture seep  路  3Comments

makc picture makc  路  3Comments