I’m trying to add three.js as a dependency to my Phoenix Project.
At the moment, I’ve vendored a minified three.js version in /assets/vendor/three.min.js
From there I added the following to my app.js:
import * as THREE from "../vendor/three.min.js";
window.THREE = THREE;
let Hooks = {};
Hooks.ThreeInit = {
mounted() {
if (this.el.dataset.initialized === "false") {
this.initThreeScene();
this.el.dataset.initialized = "true";
}
},
initThreeScene() {
// Initialize your three.js scene here, using `THREE` object.
// For example:
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
this.el.appendChild(renderer.domElement);
const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
camera.position.z = 5;
const animate = function () {
requestAnimationFrame(animate);
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render(scene, camera);
};
animate();
}
};
// other alpine stuff here
let liveSocket = new LiveSocket("/live", Socket, {
params: {_csrf_token: csrfToken},
hooks: Hooks,
dom: {
onBeforeElUpdated(from, to) {
if (from._x_dataStack) {
window.Alpine.clone(from, to)
}
}
}
})
// connect if there are any LiveViews on the page
liveSocket.connect()
The live view I am trying to render the 3D cube over is as follows:
defmodule PortfolioWeb.ThreeJSLive do
use Phoenix.LiveView
def mount(_params, _session, socket) do
{:ok, socket}
end
def render(assigns) do
~L"""
<h1>Hello, World!</h1>
<div id="three-container" phx-hook="ThreeInit"></div>
"""
end
end
At the moment, the only thing that renders is the Hello World
Any help in figuring out what the issue is would be greatly appreciated <3