Skip to content

Instantly share code, notes, and snippets.

@jasonsturges
Created December 11, 2020 19:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jasonsturges/a9f85a3b05a05bc5a538b6ef58767457 to your computer and use it in GitHub Desktop.
Save jasonsturges/a9f85a3b05a05bc5a538b6ef58767457 to your computer and use it in GitHub Desktop.
3D with Svelte and Three.js
<script>
import { onMount } from 'svelte';
import { createScene } from "./scene";
let el;
onMount(() => {
createScene(el)
});
</script>
<canvas bind:this={el}></canvas>
html, body {
width: 100%;
height: 100%;
margin: 0;
padding: 0
}
import * as THREE from 'three';
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
const cube = new THREE.Mesh(geometry, material);
let renderer;
scene.add(cube);
camera.position.z = 5;
const animate = () => {
requestAnimationFrame(animate);
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render(scene, camera);
};
const resize = () => {
renderer.setSize(window.innerWidth, window.innerHeight)
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
};
export const createScene = (el) => {
renderer = new THREE.WebGLRenderer({ antialias: true, canvas: el });
resize();
animate();
}
window.addEventListener('resize', resize);
@lalilaloe
Copy link

import * as THREE from 'three';
should be
import * as THREE from 'Three';

@AlvaroPata
Copy link

Hello! This post was very helpful, thanks a lot.

I have a question, though, how can you access the window element from _scene.js?
When I try to do that, I get a Cannot read properties of undefined (reading 'addEventListener') error.

@Chase-William
Copy link

@AlvaroPata - For my personal website, I added this file to my project to allow three.js to work as shown as I also was having the same issue.

export const ssr = false;
export const prerender = true;

@jasonsturges
Copy link
Author

@Chase-William Thanks - forgotten why I created this gist... but I have a repo of Three.js with SvelteKit here:
https://github.com/jasonsturges/threejs-sveltekit

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment