timebars.coffee 1.81 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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41

barWidth = ->
  chartWidth() / numBars()

x = d3.scale.linear().domain([ 0, 1 ]).range([ 0, barWidth() ])
y = d3.scale.linear().domain([ 0, 100 ]).rangeRound([ 0, chartHeight() ])

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

  rect.enter()
    .insert("rect", "line")
    .attr("x", (d, i) -> x i + 1 - .5)
    .attr("y", (d) -> chartHeight() - y d.value - .5)
    .attr("width", barWidth())
    .attr("height", (d) -> y d.value)
42
43
44
    .transition()
    .ease("linear")
    .duration(speed()).attr "x", (d, i) ->
45
46
47
      x(i) - .5

  rect.transition()
48
49
    .ease("linear")
    .duration(speed())
50
51
52
53
54
    .attr "x", (d, i) ->
      x(i) - .5

  rect.exit()
    .transition()
55
56
    .duration(speed() / 2)
    .style("opacity", 0)
57
58
59
    .remove()

setupChart = (containerId) ->
60
  data = d3.range(100).map(next)
61
62
63
64
65

  setInterval (->
    data.shift()
    data.push next()
    redraw()
66
  ), speed()
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91

  chart = d3.select(containerId)
    .append("svg")
      .attr("class", "chart")
      .attr("width", barWidth() * data.length - 1)
      .attr("height", chartHeight())

  chart.selectAll("rect")
    .data(data)
    .enter()
      .append("rect")
      .attr "x", (d, i) -> x(i) - .5
      .attr "y", (d) -> chartHeight() - y d.value - .5
      .attr "width", barWidth()
      .attr "height", (d) -> y d.value

  chart.append("line")
    .attr("x1", 0)
    .attr("x2", barWidth() * data.length)
    .attr("y1", chartHeight() - .5)
    .attr("y2", chartHeight() - .5)
    .style "stroke", "#000"

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