gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 04:54:28 50 4
gpt4 key购买 nike

我创建了一个 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/

50 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com