Skip to content

Instantly share code, notes, and snippets.

@oieioi
Created June 26, 2013 01:59
Show Gist options
  • Save oieioi/5864177 to your computer and use it in GitHub Desktop.
Save oieioi/5864177 to your computer and use it in GitHub Desktop.
draw fibonacci gurugurus
###
フィボナッチ渦巻きを書く
###
class window.FibUzumaki extends window.Fibonacci
###*
* コンストラクタ
* @param {object} ctx キャンバスコンテキスト
###
constructor: (@ctx) ->
super()
###*
* フィボナッチ渦巻きを出力する
* @param {number} n 渦巻きの本数
* @param {number} x 渦巻きの中心点のx座標
* @param {number} y 渦巻きの中心点のy座標
* @param {number} radius 渦巻きの角度
* @param {boolean} uzuMuki 渦巻きの向き
* @param {number} saisyo 渦巻きの最初の半径
###
drawUzumaki : (n, x, y, radius, uzuMuki, saisyo) ->
position =
x : x
y : y
i = 1
while i < n
fib = @getFib i
hankei = saisyo * fib
nextRad = @getNextRad radius, uzuMuki
@draw position.x, position.y, hankei, radius, nextRad, uzuMuki, i
# 次の準備
position = @getNextPosition position.x, position.y, radius, saisyo, i, uzuMuki
radius = nextRad
i++
###*
* 円を一つ書く
* TODO: 色を指定できるようにする
* @param {number} x 中心点x
* @param {number} y 中心点y
* @param {number} radius 半径
* @param {number} startAngle 初めの角度
* @param {number} endAngle 終わりの角度
* @param {number} anticlockwise 円の向き
* @param {number} n
###
draw : (x, y, radius, startAngle, endAngle, anticlockwise, n) ->
@ctx.beginPath()
# 色
@ctx.strokeStyle = if anticlockwise then 'rgba(0, 255, 0, 0.5)' else 'rgba(255, 0, 255, 0.5)'
# ぬりつぶし
# @ctx.fillStyle = if anticlockwise then 'rgba(0, 255, 0, 0.5)' else 'rgba(255, 0, 255, 0.5)'
# 中心に点を打つ
#@ctx.fillRect x, y, 2, 2
@ctx.arc x, y, radius, startAngle, endAngle, anticlockwise
@ctx.stroke()
###*
* 右回りか左回りに90度すすめた角度を返す
* @param {number} inRad 元の角度
* @param {boolean} uzuMuki 進める方向
* @return {number} 90度進めた角度
###
getNextRad : (inRad, uzuMuki) ->
# 時計回り
if uzuMuki
rad = inRad - ((1 / 2) * Math.PI)
# 負数になったら一周させる
# if rad < 0
# rad += 2 * Math.PI
# 反時計
else
rad = inRad + ((1 / 2) * Math.PI)
# 2パイを超えたら一周させる
# if rad > 2 * Math.PI
# rad -= 2 * Math.PI
return rad
###*
* 始点x, yと角度と距離から移動先の先の座標を返す
* @param {number} 移動元のx座標
* @param {number} 移動元のy座標
* @param {number} 渦巻きの傾き
* @param {number} 一巻き目の半径
* @param {number} 何巻目のうずか
* @param {boolean} うずの向き
* @return {object} {x:x座標,y:y座標}
###
getNextPosition : (inX, inY, rad, saisyo, n, uzuMuki) ->
fib = @getFib (n - 1)
# 移動量を計算
# cos rad = b/h
# sin rad = a/h
moveX = (Math.sin rad) * (saisyo * fib)
moveY = (Math.cos rad) * (saisyo * fib)
if uzuMuki
retPosition =
x : (inX - (moveX))
y : (inY + (moveY))
else
retPosition =
x : (inX + (moveX))
y : (inY - (moveY))
return retPosition
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment