Почему не отображается 3D модель?
Я хочу визуализировать 3D модель социальных связей друзей вконтакте с использованием Python и vk_api, так же в проекте используется JS и HTML При запуске приложения и переходе в браузер по ссылке отображается только шапка, а сама модель нет, в консоли выдает следующие:
three.min.js:1 Scripts "build/three.js" and "build/three.min.js" are deprecated with r150+, and will be removed with r160. Please use ES Modules or alternatives: https://threejs.org/docs/index.html#manual/en/introduction/Installation
(anonymous) @ three.min.js:1
OrbitControls.js:1 Uncaught ReferenceError: require is not defined
at OrbitControls.js:1:48
script.js:11 Uncaught TypeError: THREE.OrbitControls is not a constructor
at initializeVisualization (script.js:11:22)
at (index):29:9
Код приложения
server.py
from flask import Flask, render_template
from config import token, id
import vk_api
import json
# Конфигурируем Flask
app = Flask(__name__, template_folder='templates', static_folder='static')
# Вставьте сюда ваш токен доступа
TOKEN = token
def get_friends(user_id):
vk_session = vk_api.VkApi(token=TOKEN)
vk = vk_session.get_api()
friends = vk.friends.get(user_id=user_id, fields='id')
return friends['items']
def create_graph(friends):
nodes = []
edges = []
for friend in friends:
nodes.append(friend['id'])
edges.append({'source': id, 'target': friend['id']})
return nodes, edges
@app.route('/')
def home():
# Получаем список друзей пользователя
friends_list = get_friends(id)
# Создаем граф
nodes, edges = create_graph(friends_list)
# Передаем данные в шаблон
return render_template('index.html', nodes=nodes, edges=edges)
if __name__ == "__main__":
app.run(host='0.0.0.0', port=5000, debug=True)
script.js
// Функция для инициализации 3D-визуализации
function initializeVisualization(nodes, edges) {
// Создаем сцену
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
document.getElementById('graph-container').appendChild(renderer.domElement);
// Контроллер камеры
const controls = new THREE.OrbitControls(camera, renderer.domElement); // Здесь должен использоваться класс OrbitControls
// Освещение сцены
const light = new THREE.AmbientLight(0x404040); // мягкий белый свет
scene.add(light);
// Добавляем узлы
for (let node of nodes) {
const geometry = new THREE.SphereGeometry(0.1, 32, 32);
const material = new THREE.MeshPhongMaterial({ color: Math.floor(Math.random() * 0xffffff) }); // случайный цвет
const mesh = new THREE.Mesh(geometry, material);
const randomPosition = new THREE.Vector3(
Math.random() * 4 - 2, // [-2..2] по x
Math.random() * 4 - 2, // [-2..2] по y
Math.random() * 4 - 2 // [-2..2] по z
);
mesh.position.copy(randomPosition);
scene.add(mesh);
}
// Добавляем ребра
for (let edge of edges) {
const sourcePosition = nodes.find(node => node === edge.source).position;
const targetPosition = nodes.find(node => node === edge.target).position;
const curve = new THREE.CatmullRomCurve3([
sourcePosition.clone(),
targetPosition.clone()
]);
const tubeGeometry = new THREE.TubeGeometry(curve, 64, 0.01, 8, false);
const tubeMaterial = new THREE.MeshBasicMaterial({ color: 0x000000 });
const tube = new THREE.Mesh(tubeGeometry, tubeMaterial);
scene.add(tube);
}
// Настройки камеры
camera.position.z = 5;
// Рендерим сцену
function animate() {
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
animate();
}
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Социальная сеть в 3D</title>
<link rel="stylesheet" href="/static/styles.css">
<script src="https://cdn.jsdelivr.net/npm/three@^0.150/build/three.min.js"></script>
<script src="/static/OrbitControls.js"></script> <!-- Орбитальный контроллер -->
<script src="/static/script.js"></script> <!-- Наш JavaScript-код -->
</head>
<body>
<header>
<h1>Моя социальная сеть в 3D</h1>
</header>
<section id="visualisation">
<div id="graph-container"></div>
</section>
<footer>
© 2023 My Social Network
</footer>
<script>
// Получаем данные с сервера
const nodes = {{ nodes | tojson }};
const edges = {{ edges | tojson }};
// Вызываем функцию инициализации визуализации
initializeVisualization(nodes, edges);
</script>
</body>
</html>


