Canvas full screen and custom size canvas
<!-- canvas元素默认是行内块元素 -->
<div
class="model"
style="background-color: #ff0000;"
width="300"
height="180"
></div>
Canvas changes with window
// 画布跟随窗口变化
window.onresize = function () {
const width = window.innerWidth - "多余的宽度"; //model画布高度
const height = window.innerHeight - "多余的高度"; //model画布宽度
renderer.setSize(width, height);
camera.aspect = width / height;
camera.updateProjectionMatrix();
};
UI interaction buttons interact with 3D scenes
Set the model color through the button click event. I use the element-plus button here.
<el-button class="yellow-btn" type="warning" plain @click="yellowBtn"
>黄色</el-button
>
const yellowBtn = () => {
console.log(mesh);
mesh.material.color.set(0xe5a144);
};
Effect:
background transparency
.setClearAlpha()方法
renderer.setClearAlpha(0.0); // 完全透明
Set background transparencyalpha: true
// 在构造函数参数中设置alpha属性的值
var renderer = new THREE.WebGLRenderer({
alpha: true,
});
.setClearColor()方法
.setClearColor()
Parameter 2 of the method can be used to set the background color transparency.
renderer.setClearColor(0xb9d3ff, 0.4); //设置背景颜色和透明度
Here I add a background color to the div that creates the canvas
.container {
width: 100%;
height: 100vh;
position: relative;
z-index: 1;
background: #ff5810;
}
The model background needs to be deleted
// scene.background = new THREE.Color(0xaaaaaa);
At this time, the background of the model will become transparent and adapt to the background of the div.
Rendering results are saved as images
<el-button class="save-btn" @click="saveFile">下载</el-button>
const saveFile = () => {
const link = document.createElement("a");
// 通过超链接herf属性,设置要保存到文件中的数据
link.href = window.URL.createObjectURL(
new Blob([JSON.stringify(scene), JSON.stringify(mesh)])
);
link.download = "模型数据.txt"; //下载文件名
link.click(); //js代码触发超链接元素a的鼠标点击事件,开始下载文件到本地
};
After the download is completed, a txt document will be generated, containing some scene attributes and model information.
1. Configure webgl rendererpreserveDrawingBuffer:true
// WebGL渲染器设置
const renderer = new THREE.WebGLRenderer({
//想把div画布上内容下载到本地,需要设置为true
preserveDrawingBuffer: true,
});
2. Bind the click event of the button
<el-button class="save-btn" @click="saveFile">下载</el-button>
const saveFile = () => {
const saveFile = () => {
const link = document.createElement("a");
// 通过超链接herf属性,设置要保存到文件中的数据
var canvas = renderer.domElement; //获取canvas对象
link.href = canvas.toDataURL("image/png");
link.download = "threejs.png"; //下载文件名
link.click(); //js代码触发超链接元素a的鼠标点击事件,开始下载文件到本地
};
};
Effect:
3.Cavnas method.toDataURL()
const link = document.createElement('a');
// 通过超链接herf属性,设置要保存到文件中的数据
const canvas = renderer.domElement; //获取canvas对象
link.href = canvas.toDataURL("image/png");
// link.href = canvas.toDataURL("image/jpeg");
// link.href = canvas.toDataURL("image/bmp");