aboutsummaryrefslogtreecommitdiff
path: root/ps/gfx/sine.js
blob: 69582212c69c7174eed52f4712d13565a30704d4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
(function(d3) {

    const increase = ((Math.PI * 2) / 360);
    const margin   = { top:10, right:10, bottom:10, left:10 }
    const view     = d3.select('#gfx')
    const bbox     = view.node().getBoundingClientRect()
    const width    = Math.max(bbox.width, bbox.height)
    const height   = Math.max(bbox.width, bbox.height)

    var w = width - margin.right - margin.left
    var h = height - margin.top - margin.bottom

    const samples = Math.PI * 3
    var   data    = generateSineData(samples)
    
    console.log(data)

    var xScale = d3.scaleLinear().domain([0, samples-1]).range([0, w])
    var yScale = d3.scaleLinear().domain([-1, 1]).range([h, 0])

    const initialX = xScale(12);
    const initialY = yScale(15);

    // define the area
    var sine = d3.area()
	.curve(d3.curveMonotoneX)
	.x(function(d, i) { return xScale(i); })
	.y0(height)
	.y1(function(d) { return yScale(d.y || d); });

    const svg   = view.append('svg')
	  .attr('width', width + margin.left + margin.right)
	  .attr('height', height + margin.top + margin.bottom)
	  .append('g')
	  .attr('transform',function(){
              var x1 = bbox.x + bbox.width / 2
              var y1 = bbox.y + bbox.height / 2
	      console.log(`rotate(90, ${x1}, ${y1}) translate(${margin.left}, ${margin.top})`)
	      return `translate(${margin.left - x1}, ${margin.top -y1}) rotate(90, ${x1}, ${y1})`
          })
    
//    svg.append("defs").append("clipPath").attr("id", "clip")
//	.append("rect").attr("width", width).attr("height", height)
//    	.append("rect").attr("width", h).attr("height", w)    

    const graphContainer = svg.append("g")
//           .attr('transform', `translate(-${initialX}, -${initialY})`);

    const state = {
	initialX,
	initialY,
	graphContainer,
	time: 0
    };

    function generateSineData(samples) {
	return d3.range(0, 100).map(function(i) { return Math.sin(i) })
    }

    var drawSineWave = function(state) {
	const freqs = [ 84, 34, 71, 125 ]

	svg
	    .attr('width', function() { return bbox.width  })
	    .attr('height', function() {return bbox.height })

	d3.selectAll('.sinewave').remove()

	freqs.forEach(function(f, i) {
	    var data = d3.range(0, 54)
		.map(x => x * 10 / f)
		.map((x) => { return { x: x, y: - Math.sin(x + i - state.time)} })

	    state.graphContainer.append('path')
		.datum(data)
		.attr('class', 'sinewave w' + i)
		.attr('d', sine)
	})
    }
    
    var drawGraph = function(state) {
	state.time += increase;
	drawSineWave(state);
	requestAnimationFrame(drawGraph.bind(this, state));
    }

    drawGraph(state);

})(d3)