我创建了一个id为'canvas'的画布,我作为参数提供给Three.js的WebGLRenderer。但是,画布上没有任何内容出现。如果我将domElement附加到文档,画布将显示在底部,但我想在我现有的画布上绘制。我需要更改一个额外的设置吗?
我正在使用此示例代码开始:
ctx = $('canvas').getContext('2d');
var canvasElm = $('canvas');
canvasWidth = parseInt(canvasElm.width);
canvasHeight = parseInt(canvasElm.height);
canvasTop = parseInt(canvasElm.style.top);
canvasLeft = parseInt(canvasElm.style.left);
var scene = new THREE.Scene(); // Create a Three.js scene object.
var camera = new THREE.PerspectiveCamera(75, canvasWidth / canvasHeight, 0.1, 1000); // Define the perspective camera's attributes.
var renderer = window.WebGLRenderingContext ? new THREE.WebGLRenderer(canvasElm) : new THREE.CanvasRenderer(); // Fallback to canvas renderer, if necessary.
renderer.setSize(canvasWidth, canvasHeight); // Set the size of the WebGL viewport.
//document.body.appendChild(renderer.domElement); // Append the WebGL viewport to the DOM.
var geometry = new THREE.CubeGeometry(20, 20, 20); // Create a 20 by 20 by 20 cube.
var material = new THREE.MeshBasicMaterial({ color: 0x0000FF }); // Skin the cube with 100% blue.
var cube = new THREE.Mesh(geometry, material); // Create a mesh based on the specified geometry (cube) and material (blue skin).
scene.add(cube); // Add the cube at (0, 0, 0).
camera.position.z = 50; // Move the camera away from the origin, down the positive z-axis.
var render = function () {
cube.rotation.x += 0.01; // Rotate the sphere by a small amount about the x- and y-axes.
cube.rotation.y += 0.01;
renderer.render(scene, camera); // Each time we change the position of the cube object, we must re-render it.
requestAnimationFrame(render); // Call the render() function up to 60 times per second (i.e., up to 60 animation frames per second).
};
render(); // Start the rendering of the animation frames.
如果有帮助,我使用的是Chrome 56.0.2924.87(64位)。
答案 0 :(得分:0)
通过使用jQuery选择器,您将获得jQuery对象而不是原生HTMLElement。
尝试使用querySelector()
来获取画布:
var canvas = document.querySelector('canvas');
var canvasElm = $(canvas);
ctx = canvas.getContext('2d');
...
var renderer = window.WebGLRenderingContext ? new THREE.WebGLRenderer({canvas: canvas}) : new THREE.CanvasRenderer();
请注意,canvas
元素使用对象传递给了WebGLRenderer
答案 1 :(得分:0)
您的jquery选择器错误(我假设它是jquery)。
var canvasElm = $('canvas');
创建一个新的canvas元素。
如果要选择ID为'canvas'的画布,请使用..
var canvasElm = $('#canvas');
但这然后得到一个jquery对象/列表,因此可以使用实际的画布(列表中的第一项)。.
var canvasElm = $('#canvas')[0];
例如
var canvasElm = $('#canvas')[0];
renderer = new THREE.WebGLRenderer( { canvas: canvasElm } );
使用不带jquery的js可能会更好。
例如。
canvasElm = document.getElementById('canvas');
renderer = new THREE.WebGLRenderer( { canvas: canvasElm } );