threejs导出obj模型
async exportObj() {
await mFurnitureArray.forEach(async (el: any) => {
//转化为obj与mtl
let exporter = new OBJExporter();
let objData = exporter.parse(el.m_Object3D);
console.log(objData)
const objFileData = new Blob([objData], { type: 'text/plain' });
//下载文件
const a = document.createElement('a');
a.href = URL.createObjectURL(objFileData);
a.download = 'wall.obj';
a.click();
let model = el.m_Object3D;
let materials:any = [];
model.traverse(function (child: any) {
if (child.isMesh) {
// 获取子对象的材质
var material = child.material;
// 将材质添加到材质数组中
if (Array.isArray(material)) {
materials.push(...material);
} else {
materials.push(material);
}
}
});
var mtlContent = '';
for (let i = 0; i < materials.length; i++) {
// await materials.forEach(async function (material:any, index:any) {
// 材质名称
let index = i;
let material = materials[i];
mtlContent += `newmtl material_${index}\n`;
// 漫反射颜色(Diffuse Color)
material.color && (mtlContent += `Kd ${material.color.r} ${material.color.g} ${material.color.b}\n`);
// 环境光颜色(Ambient Color)
material.ambient && (mtlContent += `Ka ${material.ambient.r} ${material.ambient.g} ${material.ambient.b}\n`);
// 镜面反射颜色(Specular Color)
material.specula && (mtlContent += `Ks ${material.specular.r} ${material.specular.g} ${material.specular.b}\n`);
// 不透明度(Opacity)
mtlContent += `d ${material.opacity}\n`;
// 高光系数(Shininess)
mtlContent += `Ns ${material.shininess}\n`;
// 自发光颜色(Emission Color)
mtlContent += `Ke ${material.emissive.r} ${material.emissive.g} ${material.emissive.b}\n`;
// 可根据需要添加其他纹理贴图属性,如法线贴图、透明贴图等
const imagePath = material.map.source.data.src; // 图片路径
let toBase64 = async function (imagePath: any) {
const img = new Image();
img.src = imagePath;
img.setAttribute('crossorigin', 'anonymous');
await new Promise((resolve, reject) => {
img.onload = function () {
const canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
const ctx = canvas.getContext('2d');
ctx!.drawImage(img, 0, 0);
const dataURL = canvas.toDataURL('image/png'); // 可根据需要修改图片格式
mtlContent += `map_Kd ${dataURL}\n`;
resolve(dataURL)
};
})
}
await toBase64(imagePath)
}
// });
console.log(mtlContent)
})
return;
}