Skip to content

Instantly share code, notes, and snippets.

@mverzilli
Created October 8, 2011 22:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mverzilli/1273026 to your computer and use it in GitHub Desktop.
Save mverzilli/1273026 to your computer and use it in GitHub Desktop.
Implementation of http://www.humblesoftware.com/demos/trig_d3 in CoffeeScript
width = 760
height = 260
xmin = -1.2
xmax = 5
x_scale = d3.scale.linear()
x_scale.domain([xmin, xmax])
.range [0, width]
ymin = -height * (xmax - xmin) / width / 2
ymax = -ymin
y_scale = d3.scale.linear()
y_scale.domain([ymin, ymax])
.range [0, height]
ID_TRIG = '#trig'
vis = d3.select(ID_TRIG).append 'svg:svg'
vis.attr('class', 'trig')
.attr('width', width)
.attr 'height', height
time = 0
sine = d3.svg.line()
sine.x((d, i) -> x_scale d)
.y (d, i) -> y_scale Math.sin(d - time)
X1 = 'x1'
X2 = 'x2'
Y1 = 'y1'
Y2 = 'y2'
# X-Axis
decor = vis.append 'svg:g'
decor.append('svg:line')
.attr('class', 'axis')
.attr(X1, x_scale xmin)
.attr(Y1, y_scale 0)
.attr(X2, x_scale xmax)
.attr(Y2, y_scale 0)
decor.append('svg:line')
.attr('class', 'axis')
.attr(X1, x_scale Math.PI)
.attr(Y1, y_scale 0)
.attr(X2, x_scale Math.PI)
.attr(Y2, y_scale(0) + 8)
decor.append("svg:text")
.text(String.fromCharCode 960)
.attr("x", Math.round x_scale Math.PI)
.attr("y", y_scale(0) + 24)
.attr("text-anchor", "middle")
# Y-Axis
decor.append('svg:line')
.attr('class', 'axis')
.attr(X1, x_scale 0)
.attr(Y1, y_scale ymin)
.attr(X2, x_scale 0)
.attr(Y2, y_scale ymax)
# Graph
graph = vis.append 'svg:g'
# Time
label = graph.append 'svg:text'
label.attr("x", 2)
.attr "y", 24
# Circle
circle = graph.append 'svg:circle'
circle.attr('cx', x_scale 0)
.attr('cy', y_scale 0)
.attr('r', x_scale(1) - x_scale(0))
# Dot
dot = graph.append 'svg:circle'
dot.attr('cx', x_scale 0)
.attr('r', 4)
.style('fill', '#fff');
# Triangle
c = graph.append 'svg:line'
c.attr(X1, x_scale 0)
.attr(Y1, y_scale 0)
path = graph.append 'svg:path'
b = graph.append 'svg:line'
data = (i * 10 / 84 for i in [0..83])
draw = ->
x = x_scale Math.cos time
y = y_scale -Math.sin time
path.attr 'd', sine(data)
label.text "t = #{Math.floor(time / Math.PI)}"
c.attr(X2, x)
.attr(Y2, y)
b.attr(X1, x_scale 0)
.attr(Y1, y)
.attr(X2, x)
.attr(Y2, y)
dot.attr('cy', y)
time += .015
setTimeout draw, 35
draw()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment