ByteMuse.com

The code and musings of @ChrisPolis

About Posts Contact

Animated Fibonacci Spiral in SVG

May 19th, 2014

The Fibonacci sequence (1, 1, 2, 3, 5 ... Fn where Fn = Fn-1+Fn-2) and the Golden Ratio fascinate me. The sequence can be iterated with a slick one-liner in CoffeeScript (or other languages that support this kind of assignment):

[fib, fibNext] = [fibNext, fib+fibNext]

Click below to redraw

Source

#
width      = $('.container').width()
iterations = 14
scale      = width * .0016
dAttr      = "m#{width * .29},#{width * .2}"

#
svg = d3.select('#fib-vis')
  .append 'svg'
  .attr   'width', width
  .attr   'height', width * 0.64
  .append  'g'

# SVG elliptical arc curve (in <path> d attribute):
#  a (rx, ry, x-axis-rotation, large-arc-flag, sweep-flag, x, y)
[fib, fibNext] = [1, 1]
for ndx in [0...iterations]
  r = fib * scale
  x = if ndx % 4 < 2 then r else r * -1
  y = if (ndx + 1) % 4 < 2 then r else r * -1
  dAttr += "a#{r},#{r} 0 0 0 #{x},#{y}"
  [fib, fibNext] = [fibNext, fib+fibNext]
path = svg.append('path').attr 'd', dAttr

#
length = path.node().getTotalLength()
window.draw = () ->
  path
    .attr 'stroke-dasharray', "#{length} #{length}"
    .attr 'stroke-dashoffset', length
    .transition()
      .duration 5 * 1000
      .ease 'cubic-in'
      .attr 'stroke-dashoffset', 0
setTimeout(draw, 500)

Tweet
Fib preview

© Chris Polis, 2012 - 2016

GitHub · Twitter · LinkedIn · Stack Overflow · Quora