Skip to content

Instantly share code, notes, and snippets.

@teliosdev
Forked from Mechazawa/index.html
Last active August 29, 2015 13:58
Show Gist options
  • Save teliosdev/10209475 to your computer and use it in GitHub Desktop.
Save teliosdev/10209475 to your computer and use it in GitHub Desktop.
<html>
<head>
<title>Sierpinski triangles in Liquidscript</title>
<script src="triangles.js"></script>
<style>html { background-color: #f9f9f9; }</style>
</head>
<body onload="sierpinski(256)">
<canvas id="result" width="800" height="800"></canvas>
</body>
</html>
#! allow Math Array document
triangle-log = -> {
console.log("[triangle]", arguments)
}
class Triangle {
initialize: (canvas) ->
this.canvas = canvas
init: -> {
ctx = this.canvas.get-context('2d)
this.canvas.width = this.canvas.width # Clear the canvas
ctx.fill-style = ctx.stroke-style = "#88a6cf"
return ctx
}
height: ->
return this.data.length
scale: (ctx) -> {
ctx.scale(0.5, 0.5)
return 0.5
}
generate: (height) -> {
this.data = new Array()
this.data.push([1])
this.data.push(new Array(1, 1))
for(i = 2, i < height, i++) {
c-row = [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]
c-row.push((l + r) % 2)
}
c-row.push(1)
this.data.push(c-row)
}
}
draw: -> {
h = this.height()
ctx = this.init()
scale = this.scale(ctx)
for(y = 0, y < h, y++) {
for(x = 0, x < this.data[y].length, x++) {
if (0 != this.data[y][x]) {
ctx.begin-path()
ctx.arc(h - this.data[y].length + x * 2 + 1, y * 2 + 1, 1, 0, Math.PI * 2)
ctx.fill()
ctx.close-path()
}
}
}
}
}
window.sierpinski = (h) -> {
triangle = new Triangle(document.get-element-by-id("result"))
triangle-log(h, triangle)
triangle.generate(h)
triangle.draw()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment