Three.js 当HTML画布与drawImage结合使用时,将呈现空白纹理
我试图从url加载一个图像,并将其绘制到画布上,画布用作纹理的输入。我已经在上实现了这一点。我使用了下面的代码片段来加载图像并创建纹理Three.js 当HTML画布与drawImage结合使用时,将呈现空白纹理,three.js,textures,Three.js,Textures,我试图从url加载一个图像,并将其绘制到画布上,画布用作纹理的输入。我已经在上实现了这一点。我使用了下面的代码片段来加载图像并创建纹理 var img = new Image(); img.onload = function() { canvas.width = size; canvas.height = size; ctx.drawImage(this, 0, 0, size, size); if(texture) {
var img = new Image();
img.onload = function() {
canvas.width = size;
canvas.height = size;
ctx.drawImage(this, 0, 0, size, size);
if(texture)
{
texture.needsUpdate = true;
}
};
img.src = "https://threejsfundamentals.org/threejs/resources/images/wall.jpg";
texture = new THREE.Texture(canvas);
请有人给我指出错误 问题可能在于,由于您自己加载图像,并且是从另一个域加载图像,因此您需要请求使用该图像的权限
var img = new Image();
img.onload = function() {
canvas.width = size;
canvas.height = size;
ctx.drawImage(this, 0, 0, size, size);
if(texture)
{
texture.needsUpdate = true;
}
};
img.crossOrigin = 'anonymous'; // ----------- Add this line
img.src = "https://threejsfundamentals.org/threejs/resources/images/wall.jpg";
texture = new THREE.Texture(canvas);
请注意,添加该行不会自动允许您使用来自其他网站的图像。相反,它要求该网站允许使用该图像。一些网站(imgur、flickr、github、threejsfundamentals.org)给予该权限。大多数网站不授予权限。如果映像位于同一域上,则通常不希望设置交叉源
,否则,除非您的服务器配置为授予权限,否则您将无法使用本地映像,而正常情况下,如果您不请求,则本地映像只起作用
此外,如果打开JavaScript控制台,您会看到此错误
three.min.js:572 Uncaught DOMException: Failed to execute 'texImage2D'
on 'WebGLRenderingContext': Tainted canvases may not be loaded.
还有一件事,您可以使用三个.js来处理此权限问题,如果图像位于另一个域,则自动设置crossDomain
,如果图像位于本地,则不设置
const loader = new THREE.ImageLoader();
loader.load("https://threejsfundamentals.org/threejs/resources/images/wall.jpg", function() {
canvas.width = size;
canvas.height = size;
ctx.drawImage(this, 0, 0, size, size);
if(texture)
{
texture.needsUpdate = true;
}
});