<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<style>
body { margin: 0; }
canvas { display: block; }
</style>
</head>
<body>
<script src="./main.js"></script>
<button id="download" type="button">下载</button>
</body>
</html>
index.html
main.js
package.json
现在支持上传本地图片了!
import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
const width = window.innerWidth;
const height = window.innerHeight;
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, width / height, 0.1, 3000);
const renderer = new THREE.WebGLRenderer({
preserveDrawingBuffer: true, // 想把canvas画布上内容下载到本地,需要设置为true
});
const geometry = new THREE.BoxGeometry(100, 100, 100);
const material = new THREE.MeshPhongMaterial({
color: '#049ef4',
transparent: true,
opacity: 0.6,
});
const mesh = new THREE.Mesh(geometry, material);
const pointLight = new THREE.DirectionalLight('#fff', 1); // 点光源
const ambientLight = new THREE.AmbientLight(0x404040, 2); // 环境光
const directionalLight = new THREE.DirectionalLight(0xffffff, 1); // 方向光
const pointLightHelper = new THREE.PointLightHelper(pointLight, 10); // 光源辅助观察
const controls = new OrbitControls(camera, renderer.domElement);
pointLight.position.set(-200, 200, 200);
pointLight.castShadow = true;
directionalLight.position.set(5, 5, 5).normalize();
directionalLight.castShadow = true;
scene.add(mesh);
scene.add(pointLight);
scene.add(ambientLight);
scene.add(directionalLight);
scene.add(pointLightHelper);
camera.position.set(-300, 200, 200); // x,y,z
camera.lookAt(mesh.position); // 相机视角: 指向mesh设置的位置(中心点)
renderer.setSize(width, height);
renderer.setClearColor(0x444444, 1);
renderer.render(scene, camera);
document.body.appendChild(renderer.domElement);
const saveFile = () => {
const canvas = renderer.domElement;
const link = document.createElement('a');
link.href = canvas.toDataURL('image/jpeg');
link.download = 'test';
link.click();
}
document.getElementById('download').addEventListener('click', saveFile)
controls.addEventListener('change', () => {
renderer.render(scene, camera);
})
{
"dependencies": {
"three": "0.173.0"
}
}
预览