1. 目的
Three.js で立方体を描く。
2. デモ
3. ソースコード
let scene, camera, cube, renderer;
window.onload = ()=>{
const canvasElement = document.querySelector('#three');
// Sceneを作成
scene = new THREE.Scene();
scene.background = new THREE.Color(0xffffff);
// Cameraを作成
camera = new THREE.PerspectiveCamera(
68, canvasElement.offsetWidth / window.innerHeight, 0.1, 1000);
camera.position.z = 20;
// Rendererを作成
renderer = new THREE.WebGLRenderer();
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(canvasElement.offsetWidth, window.innerHeight);
canvasElement.appendChild(renderer.domElement);
// 立方体のサイズと間隔を設定
const geometry = new THREE.BoxGeometry(2, 2, 2);
const numCubesX = 8;
const numCubesY = 6;
const spacing = 3.2;
// カラー計算用のヘルパー関数
function calculateColor(lightness, x, y) {
const maxDistance = Math.sqrt(
Math.pow((numCubesX - 1) / 2 * spacing, 2) +
Math.pow((numCubesY - 1) / 2 * spacing, 2)
);
const distance = Math.sqrt(x * x + y * y);
const ratio = distance / maxDistance;
const range = 90 - lightness;
const newLightness = Math.round(range * ratio);
return lightness + newLightness;
}
let color1, color2, color3, color4, color5, color6;
for (let i = 0; i < numCubesX; i++) {
for (let j = 0; j < numCubesY; j++) {
const x = i * spacing - (numCubesX - 1) * spacing / 2;
const y = j * spacing - (numCubesY - 1) * spacing / 2;
color1 = calculateColor(50, x, y);
color2 = calculateColor(50, x, y);
color3 = calculateColor(50, x, y);
color4 = calculateColor(50, x, y);
color5 = calculateColor(39, x, y);
color6 = calculateColor(50, x, y);
const materials = [
new THREE.MeshBasicMaterial({ color: `hsla(240, 100%, ${color1}%, 1)` }),//濃い青
new THREE.MeshBasicMaterial({ color: `hsla(186, 100%, ${color2}%, 1)` }),//水色
new THREE.MeshBasicMaterial({ color: `hsla(60, 100%, ${color3}%, 1)` }),//黄色
new THREE.MeshBasicMaterial({ color: `hsla(270, 100%, ${color4}%, 1)` }),//紫
new THREE.MeshBasicMaterial({ color: `hsla(143, 100%, ${color5}%, 1)` }),//黄緑
new THREE.MeshBasicMaterial({ color: `hsla(180, 100%, ${color6}%, 1)` }) //水色
];
cube = new THREE.Mesh(geometry, materials);
cube.position.x = x;
cube.position.y = y;
scene.add(cube);
}
}
animate();
}
function animate() {
requestAnimationFrame(animate);
renderer.render(scene, camera);
}