Created
December 11, 2020 19:24
-
-
Save jasonsturges/a9f85a3b05a05bc5a538b6ef58767457 to your computer and use it in GitHub Desktop.
3D with Svelte and Three.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script> | |
import { onMount } from 'svelte'; | |
import { createScene } from "./scene"; | |
let el; | |
onMount(() => { | |
createScene(el) | |
}); | |
</script> | |
<canvas bind:this={el}></canvas> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
html, body { | |
width: 100%; | |
height: 100%; | |
margin: 0; | |
padding: 0 | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
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.
@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;
@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
import * as THREE from 'three';
should be
import * as THREE from 'Three';