Files
isdefoobaropen/src/open.js
2019-03-08 18:13:47 +01:00

118 lines
3.2 KiB
JavaScript

import * as THREE from "three";
import './open.scss';
const STAR_POINTS = 5;
let scene, camera, renderer;
let group;
function addStar() {
let geometry = new THREE.BufferGeometry();
let vertices = starCoordinates(2 / 3, 1, 0);
geometry.addAttribute('position', new THREE.BufferAttribute(vertices, 3));
geometry.setIndex(filledStarIndices());
let material = new THREE.MeshBasicMaterial({color: 0x00ff00});
material.side = THREE.DoubleSide;
let star = new THREE.Mesh(geometry, material);
group.add(star);
}
function startOpenAnimation() {
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.z = 5;
renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
group = new THREE.Group();
scene.add(group);
addStar();
loadFont();
requestAnimationFrame(animate)
}
function loadFont() {
import('../node_modules/three/examples/fonts/helvetiker_bold.typeface').then(function (data) {
let font = new THREE.Font(data);
let geometry = new THREE.TextGeometry('Ja!', {
font: font,
size: 0.5,
height: 0.1,
curveSegments: 12
}).center();
let textMaterial = new THREE.MeshBasicMaterial({color: 0xff00ff});
let mesh = new THREE.Mesh(geometry, textMaterial);
group.add(mesh);
});
}
/**
* Construct the vertex indices needed to create a filled star.
* @returns {Number[]}
*/
function filledStarIndices() {
const buf = Array(2 * STAR_POINTS * 3);
const TOTAL_VERTICES = 2 * STAR_POINTS;
// First, the "points" of the star.
for (let i = 0; i < STAR_POINTS; ++i) {
const offset = 3 * i;
buf[offset] = 2 * i;
buf[offset + 1] = 2 * i + 1;
buf[offset + 2] = (2 * i + TOTAL_VERTICES - 1) % (TOTAL_VERTICES);
}
// Then, the inner part, constructed from opposing triangles.
for (let i = 0; i < STAR_POINTS; ++i) {
const offset = 3 * (STAR_POINTS + i);
buf[offset] = 2 * i + 1;
buf[offset + 1] = (2 * i + 3) % TOTAL_VERTICES;
buf[offset + 2] = (2 * i + 3 + 2 * Math.floor(STAR_POINTS / 2)) % (TOTAL_VERTICES);
}
return buf;
}
/**
* Generate the outer points of an N pointed star.
*
* @param innerRadius
* @param outerRadius
* @param z
* @returns {Float32Array}
*/
function starCoordinates(innerRadius, outerRadius, z) {
const buf = new Float32Array(3 * STAR_POINTS * 2);
const STAR_SLICE = 2 * Math.PI / STAR_POINTS;
for (let i = 0; i < STAR_POINTS; ++i) {
const offset = 3 * 2 * i;
buf[offset + 0] = Math.sin(STAR_SLICE * i) * outerRadius;
buf[offset + 1] = Math.cos(STAR_SLICE * i) * outerRadius;
buf[offset + 3] = Math.sin(STAR_SLICE * (i + 0.5)) * innerRadius;
buf[offset + 4] = Math.cos(STAR_SLICE * (i + 0.5)) * innerRadius;
buf[offset + 5] = buf[offset + 2] = z;
}
return buf;
}
function animate() {
requestAnimationFrame(animate);
group.rotation.z += 0.01;
group.rotation.y += 0.01;
renderer.render(scene, camera);
}
export {startOpenAnimation};