[英]Rotating textures using canvas with Three.js
我想使用Three.js旋转出现在多维数据集的一个面上的纹理。
由于此多维数据集使用不同的纹理多次创建,因此我使用了一个函数,该函数使用纹理参数创建材质和网格。
但是,我需要将此纹理旋转90°,我发现最好的方法是创建一个画布,将其放入其中,旋转它,然后将该画布用作网格纹理。 我尝试使用以下代码来实现这一点: Three.js Rotate Texture ,但是不幸的是我总是得到黑色的纹理。
这是我的功能:
function createCube(pos, texture) {
var img = new Image();
img.src = texture;
var imgWidth = imgHeight = img.width;
var mapCanvas = document.createElement( 'canvas' );
mapCanvas.width = mapCanvas.height = img.width;
// document.body.appendChild( mapCanvas );
var ctx = mapCanvas.getContext( '2d' );
ctx.translate( imgWidth / 2, imgHeight / 2 );
ctx.rotate( Math.PI / 2 );
ctx.translate( -imgWidth / 2, -imgHeight / 2 );
ctx.drawImage( img, 0, 0, imgWidth, imgHeight );
var texture = new THREE.Texture( mapCanvas );
texture.needsUpdate = true;
var materials = [
//Left side (posx)
new THREE.MeshLambertMaterial({
color: 0x1a0e05
}),
//Right side (negx)
new THREE.MeshLambertMaterial({
color: 0x1a0e05
}),
//Top side (posy)
new THREE.MeshLambertMaterial({
color: 0x1a0e05
}),
//Bottom side (negy)
new THREE.MeshLambertMaterial({
color: 0xffffff,
map: texture
}),
//Front side (posz)
new THREE.MeshLambertMaterial({
color: 0x1a0e05
}),
//Back side (negz)
new THREE.MeshLambertMaterial({
color: 0x1a0e05
})
];
cube = new THREE.Mesh(new THREE.CubeGeometry(100, 2, 100, 1, 1, 1), new THREE.MeshFaceMaterial(materials));
...
return cube;
}
也许是由于贴在画布上时尚未加载纹理导致的? 我删除了img.onLoad
(来自Three.js的Rotate Texture ),因为我不知道如何多次在函数中使用该回调函数。此外,该函数还可以返回网格,我可以使用extern来做到这一点。 .onLoad
功能?
谢谢 !
您的猜测“由于贴在画布上时尚未加载纹理”绝对是正确的。
您只需要重新引入回调,就需要对代码进行一些重新排序。 应该像这样工作(未经测试,但如果不能立即工作,则应使思路清晰):
function createCube(pos, texture) {
var img = new Image();
var imgWidth = imgHeight = img.width;
var mapCanvas = document.createElement( 'canvas' );
mapCanvas.width = mapCanvas.height = img.width;
var texture = new THREE.Texture( mapCanvas );
img.onload = function() {
// document.body.appendChild( mapCanvas );
var ctx = mapCanvas.getContext( '2d' );
ctx.translate( imgWidth / 2, imgHeight / 2 );
ctx.rotate( Math.PI / 2 );
ctx.translate( -imgWidth / 2, -imgHeight / 2 );
ctx.drawImage( img, 0, 0, imgWidth, imgHeight );
texture.needsUpdate = true;
}
var materials = [
//Left side (posx)
new THREE.MeshLambertMaterial({
color: 0x1a0e05
}),
//Right side (negx)
new THREE.MeshLambertMaterial({
color: 0x1a0e05
}),
//Top side (posy)
new THREE.MeshLambertMaterial({
color: 0x1a0e05
}),
//Bottom side (negy)
new THREE.MeshLambertMaterial({
color: 0xffffff,
map: texture
}),
//Front side (posz)
new THREE.MeshLambertMaterial({
color: 0x1a0e05
}),
//Back side (negz)
new THREE.MeshLambertMaterial({
color: 0x1a0e05
})
];
img.src = texture;
cube = new THREE.Mesh(new THREE.CubeGeometry(100, 2, 100, 1, 1, 1), new THREE.MeshFaceMaterial(materials));
...
return cube;
}
您需要具有渲染循环,或者也可以在onload回调中重新渲染场景。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.