Last active
March 22, 2024 19:05
-
-
Save quidmonkey/2d0182d68cc90e49cdf1 to your computer and use it in GitHub Desktop.
Three.js Mandelbrot Demo
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
<!DOCTYPE html> | |
<html> | |
<head> | |
<script src="//cdnjs.cloudflare.com/ajax/libs/three.js/r67/three.min.js"></script> | |
</head> | |
<body> | |
<script id="mandelbrot-vertex" type="x-shader/x-vertex"> | |
precision highp float; | |
uniform float zoom; | |
varying vec2 pos; | |
void main () { | |
pos = position.xy * zoom; | |
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); | |
} | |
</script> | |
<script id="mandelbrot-fragment" type="x-shader/x-fragment"> | |
precision highp float; | |
varying vec2 pos; | |
void main () { | |
vec2 fractal = pos; | |
for (int i = 0; i < 20; i++) { | |
fractal = pos + vec2( | |
fractal.x * fractal.x - fractal.y * fractal.y, | |
2.0 * fractal.x * fractal.y | |
); | |
// interpolate fractal color over position | |
gl_FragColor = vec4(fractal, 0, 1); | |
// if outside of fractal, use black | |
if (length(fractal) > 1.5) { | |
gl_FragColor = vec4(0, 0, 0, 1); | |
} | |
} | |
} | |
</script> | |
<script type="text/javascript"> | |
var width = window.innerWidth; | |
var height = window.innerHeight; | |
var scene = new THREE.Scene(); | |
var camera = new THREE.PerspectiveCamera(75, width / height, 0.1, 1000); | |
camera.position.z = 1; | |
// create canvas | |
var renderer = new THREE.WebGLRenderer(); | |
renderer.setSize(width, height); | |
document.body.appendChild(renderer.domElement); | |
// create mandelbrot mesh | |
var geometry = new THREE.PlaneGeometry(2, 2, 0); | |
var material = new THREE.ShaderMaterial({ | |
uniforms: { | |
zoom: { type: 'f', value: 0.05 } | |
}, | |
vertexShader: document.getElementById('mandelbrot-vertex').innerHTML, | |
fragmentShader: document.getElementById('mandelbrot-fragment').innerHTML | |
}); | |
var mesh = new THREE.Mesh(geometry, material); | |
scene.add(mesh); | |
function render (delta) { | |
requestAnimationFrame(render); | |
mesh.material.uniforms.zoom.value = Math.cos(delta / 500) + 1.5; | |
renderer.render(scene, camera); | |
} | |
render(); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment