Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/three.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
three.js未能使用预先创建的画布_Three.js - Fatal编程技术网

three.js未能使用预先创建的画布

three.js未能使用预先创建的画布,three.js,Three.js,我想使用预先创建的画布和three.js。从我阅读的教程和其他帖子中,这应该是可行的: const canvas = document.createElement('canvas'); const ctx = canvas.getContext("2d"); // <--- This causes the error below! const renderer = new THREE.WebGLRenderer( { canvas: canvas } ); 我还

我想使用预先创建的画布和three.js。从我阅读的教程和其他帖子中,这应该是可行的:

const canvas = document.createElement('canvas');
const ctx = canvas.getContext("2d");    // <--- This causes the error below!
const renderer = new THREE.WebGLRenderer( { canvas: canvas } );
我还尝试添加

<canvas id='myCanvas'></canvas>
确保DOM已加载,等等

如果我删除
getContext(“2d”)
行,那么它会工作吗

我使用的是three.js版本0.120


为什么这会导致问题?

Three.js只在一个地方抛出这个错误,幸运的是它做了一件非常简单的事情:从
画布
获取上下文。它使用
htmlcanvaseElement.getContext
来执行此操作,并且仅当结果为
null
时才会抛出错误

将只允许您请求一种上下文类型。您可以再次请求相同的类型(或兼容,在
webgl
webgl2
的情况下),但它将返回在画布上创建的原始上下文。在第一个请求建立使用中上下文后,不兼容类型的后续请求将返回
null

让ctx_2d_1=mycanvas.getContext('2d')
让ctx_2d_2=mycanvas.getContext('2d')
console.log(ctx_2d_1==ctx_2d_2)//true
让ctx_2d=mycanvas.getContext('2d')
让ctx_webgl=mycanvas.getContext('webgl')
console.log(ctx_2d)//canvasrendingcontext2d
console.log(ctx_webgl)//null
让ctx_webgl=mycanvas.getContext('webgl')
让ctx_2d=mycanvas.getContext('2d')
console.log(ctx_webgl)//WebGLRenderingContext
console.log(ctx_2d)//null
由于在调用
WebGLRenderer
构造函数之前要创建
2d
上下文,因此构造函数无法从画布中获取有效的
WebGLRenderingContext
。相反,它会得到一个
null
,因此会抛出错误


如果您想在3D之上绘制2D(反之亦然),则需要将不同背景的画布分层,或使用平面在WebGL(three.js)背景中将2D信息渲染为纹理。

对我来说效果不错(r122,Chrome 86)。我去了,然后打开了一个控制台。我输入:
let c=document.createElement('canvas');设r=new-THREE.WebGLRenderer({canvas:c})一切顺利。更新我上面的问题。。。这很奇怪。是的,代码是有效的。如果我添加
ctx=canvas.getContext(“2d”)则失败。不认为这是相关的,因此不包括上述内容…忽略我目前的答案。。。我正在根据这个新信息更新它。新答案发布了。根据您的评论,听起来您需要找到一种不同的方法来做您想做的事情。谢谢,这是可行的,但会带来一个新问题,因为WebGL上下文不允许我使用drawImage()。让我重温一下我正在尝试做的事情,看看是否能找到一种不同的方法。谢谢@TheJim01。我想知道如何把画布分层。你能告诉我一个好的来源吗?@mstreffo这将通过CSS定位和z索引完成。无论您最喜欢的HTML/CSS教程网站是什么,都应该足够好了。:)
<canvas id='myCanvas'></canvas>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");    // <--- This causes the same error!
const renderer = new THREE.WebGLRenderer({
   canvas: canvas,
});
window.onload = function() {
  ...
};