javascript - Three.js 未在现有 Canvas 上渲染

标签 javascript canvas three.js

我创建了一个 ID 为“canvas”的 Canvas ,并将其作为参数提供给 Three.js 的 WebGLRenderer。然而, Canvas 上什么也没有显示。如果我将 domElement 附加到文档中, Canvas 将显示在底部,但我想在现有的 Canvas 上绘图。我需要更改额外的设置吗?

我使用此示例代码开始:

  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 位)。

最佳答案

你的jquery选择器是错误的(我假设它是jquery)。
var canvasElm = $('canvas'); 创建一个新的 canvas 元素。
如果您想选择 id 为“canvas”的 Canvas ,请使用..
var canvasElm = $('#canvas');
但这会获取一个 jquery 对象/列表,因此要获取实际的 Canvas (列表中的第一项),您可以使用..
var canvasElm = $('#canvas')[0];

例如。

var canvasElm = $('#canvas')[0];
renderer = new THREE.WebGLRenderer( { canvas: canvasElm } );

只使用 js 而不使用 jquery 可能会更好。
例如。

canvasElm = document.getElementById('canvas');
renderer = new THREE.WebGLRenderer( { canvas: canvasElm } );

关于javascript - Three.js 未在现有 Canvas 上渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42494770/

相关文章:

javascript - 如何让 GSAP 时间线识别在其中创建的元素?

javascript - 添加另一个形状时,动力学 JS 形状阴影变得更加明显

javascript - 事件上的鼠标指针位置未以 THREE.js 上的箭头提示为中心

三.js OrbitControls。如何更新旋转相机?

javascript - 在 Three.js 中渲染复杂模型

javascript - jQuery如何使用td背景颜色

javascript - 计算具有 2 种颜色和百分比/位置的颜色 HEX

javascript - 是否可以将函数分配给对象实例本身?

javascript - onBlur 杀死 onClick 但如果使用 setTimeout 则不会

javascript - 将 C++ 代码连接到 Electron 应用程序中的 HTML Canvas ?