Skip to content

Instantly share code, notes, and snippets.

@tmcw
Created May 8, 2012 22:26
Show Gist options
  • Save tmcw/2639929 to your computer and use it in GitHub Desktop.
Save tmcw/2639929 to your computer and use it in GitHub Desktop.
Gosper Curve
<!DOCTYPE html>
<html>
<head>
<title>noises</title>
<meta name="viewport" content="width=320; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;"/>
</head>
<body>
<style type='text/css'>
body {
margin:0;
padding:0;
font:12px/20px 'Helvetica';
}
div {
float:left;
padding:5px;
}
</style>
<script type='text/javascript'>
window.onload = function() {
var container = document.body.appendChild(document.createElement('div'));
var c = container.appendChild(document.createElement('canvas'));
var ctx = c.getContext('2d');
c.width = 1000;
c.height = 1000;
ctx.fillStyle = '#fff';
ctx.fillRect(0, 0, 1000, 1000);
var turtle = [0, 0, 0];
function rt(x) {
turtle[2] += x;
}
function lt(x) {
turtle[2] -= x;
}
ctx.strokeStyle = '#111';
function fd(dist) {
ctx.beginPath();
ctx.moveTo(turtle[0], turtle[1]);
var dir = turtle[2] * (Math.PI/180);
turtle[0] += Math.cos(dir) * dist;
turtle[1] += Math.sin(dir) * dist;
ctx.lineTo(turtle[0], turtle[1]);
ctx.stroke();
}
function rg(st, ln, turtle) {
st--;
ln = ln / 2.6457;
if (st > 0) {
ctx.strokeStyle = '#111';
rg(st, ln, turtle);
rt(60);
gl(st, ln, turtle);
rt(120);
gl(st, ln, turtle);
lt(60);
rg(st, ln, turtle);
lt(120);
rg(st, ln, turtle);
rg(st, ln, turtle);
lt(60);
gl(st, ln, turtle);
rt(60);
}
if (st == 0) {
fd(ln)
rt(60)
fd(ln)
rt(120)
fd(ln)
lt(60)
fd(ln)
lt(120)
fd(ln)
fd(ln)
lt(60)
fd(ln)
rt(60)
}
}
function gl(st, ln, turtle) {
st--;
ln = ln / 2.6457;
if (st > 0) {
ctx.strokeStyle = '#555';
lt(60);
rg(st, ln, turtle);
rt(60);
gl(st, ln, turtle);
gl(st, ln, turtle);
rt(120);
gl(st, ln, turtle);
rt(60);
rg(st, ln, turtle)
lt(120)
rg(st, ln, turtle);
lt(60);
gl(st, ln, turtle);
}
if (st == 0) {
lt(60);
fd(ln);
rt(60);
fd(ln);
fd(ln);
rt(120)
fd(ln);
rt(60);
fd(ln);
lt(120);
fd(ln);
lt(60);
fd(ln);
}
}
ctx.translate(600, 100);
rg(5, 600, turtle);
ctx.restore();
}
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment