timebars.coffee 1.61 KB
Newer Older
Kjetil Thuen's avatar
Kjetil Thuen committed
1
2
d3 = require 'd3-browserify'
lodash = require 'lodash'
3
4
5
6
7
8
9
10
11
12
13
14

chart = null
data = []

t = 1297110663
v = 0

next = ->
  time: ++t
  value: v = ~~Math.max(10, Math.min(90, v + 10 * (Math.random() - .5)))

chartWidth = ->
15
  900
16
17

chartHeight = ->
18
  500
19
20

numBars = ->
21
22
23
24
  100

speed = ->
  500
25
26

barWidth = ->
Kjetil Thuen's avatar
Kjetil Thuen committed
27
  chartHeight() / numBars()
28

Kjetil Thuen's avatar
Kjetil Thuen committed
29
30
31
32
33
34
35
x = d3.scale.linear()
  .domain([ 9, 91])
  .range([ 0, chartWidth() / 2 ])

y = d3.scale.linear()
  .domain([ 0, numBars()])
  .rangeRound([ 0, chartHeight() ])
36
37
38
39
40
41
42

redraw = ->
  rect = chart.selectAll("rect")
    .data(data, (d) -> d.time)

  rect.enter()
    .insert("rect", "line")
Kjetil Thuen's avatar
Kjetil Thuen committed
43
44
45
46
    .attr "x", chartWidth() / 2
    .attr "y", (d, i) -> y(i) + .5
    .attr("width", (d) -> x(d.value))
    .attr("height", barWidth())
47
48
49
    .transition()
    .ease("linear")
    .duration(speed()).attr "x", (d, i) ->
50
51
52
      x(i) - .5

  rect.transition()
53
54
    .ease("linear")
    .duration(speed())
Kjetil Thuen's avatar
Kjetil Thuen committed
55
    .attr "y", (d, i) ->
56
57
58
59
      x(i) - .5

  rect.exit()
    .transition()
60
61
    .duration(speed() / 2)
    .style("opacity", 0)
62
63
64
    .remove()

setupChart = (containerId) ->
Kjetil Thuen's avatar
Kjetil Thuen committed
65
  data = d3.range(numBars()).map(next)
66
67
68
69
70

  setInterval (->
    data.shift()
    data.push next()
    redraw()
71
  ), speed()
72
73
74
75

  chart = d3.select(containerId)
    .append("svg")
      .attr("class", "chart")
Kjetil Thuen's avatar
Kjetil Thuen committed
76
      .attr("width", chartWidth())
77
78
79
80
81
82
      .attr("height", chartHeight())

  chart.selectAll("rect")
    .data(data)
    .enter()
      .append("rect")
Kjetil Thuen's avatar
Kjetil Thuen committed
83
84
85
86
      .attr "x", chartWidth() / 2
      .attr "y", (d, i) -> y(i) + .5
      .attr("width", (d) -> x(d.value))
      .attr("height", barWidth())
87
88
89

window.initTimeBars = (containerId) ->
  setupChart(containerId)