Skip to content

Instantly share code, notes, and snippets.

@Mechazawa
Created April 8, 2014 23:03
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 Mechazawa/10206235 to your computer and use it in GitHub Desktop.
Save Mechazawa/10206235 to your computer and use it in GitHub Desktop.
sierpinski triangles
<html>
<head>
<title>Sierpinski triangles in Liquidscript</title>
<script src="triangle.js"></script>
</head>
<body onload="sierpinski(100)">
<canvas id="result" width="800" height="800"></canvas>
</body>
</html>
#! allow Math Array document
class Triangle {
initialize: (canvas) ->
this.canvas = canvas
init: ()-> {
ctx = this.canvas.getContext('2d')
this.canvas.width = this.canvas.width # Clear the canvas
ctx.strokeStyle = "#000"
return ctx
}
height: ->
return this.data.length
scale: (ctx, height) -> {
scale = this.canvas.width / 2 / height
ctx.scale(scale, scale)
return scale
}
generate: (height) -> {
this.data = new Array()
this.data.push([1])
this.data.push(new Array(1, 1))
for(i = 2, i < height, i++) {
cRow = [1]
for(j = 0, j < (this.data[i - 1].length - 1), j++){
l=this.data[i - 1][j]
r=this.data[i - 1][j + 1]
cRow.push((l + r) % 2)
}
cRow.push(1)
this.data.push(cRow)
}
}
draw: -> {
h = this.height()
ctx = this.init()
scale = this.scale(ctx, h)
for(y = 0, y < h, y++){
for(x = 0, x < this.data[y].length, x++){
if (0 != this.data[y][x]) {
ctx.beginPath()
ctx.arc(h - this.data[y].length + x * 2 + 1, y * 2 + 1, 1, 0, Math.PI * 2)
ctx.fill()
}
}
}
}
}
sierpinski = (h) -> {
triangle = new Triangle(document.getElementById("result"))
triangle.generate(h)
triangle.draw()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment