Skip to content

Instantly share code, notes, and snippets.

@tomgp
Created January 29, 2018 15:44
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 tomgp/fa89ebb5e14d62f9d1aeaa3594f43262 to your computer and use it in GitHub Desktop.
Save tomgp/fa89ebb5e14d62f9d1aeaa3594f43262 to your computer and use it in GitHub Desktop.
sine oscilator

A little function that makes a sine wave generator with some simple properties: the range over which it varies and the wavelength

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Test</title>
<script src="https://d3js.org/d3.v5.min.js"></script>
<script src="index.js"></script>
</head>
<body>
<svg width="500" height="500"></svg>
</body>
<script>
//default is that it oscilates between -1 and 1
//with one complete oscilation hapening every 1 unit of time
function makeSinOscilator(range=[-1,1], waveLength = 1){
waveLength = waveLength/(2*Math.PI);
const scaleX = d3.scaleLinear()
.domain([-1,1])
.range(range)
return (time) => scaleX( Math.sin(time/waveLength) );
}
const myOsc = makeSinOscilator([-2,2],0.5);
const values = [];
for(let t = 0; t<1; t += 0.01){
values.push({x:t, y:myOsc(t)});
}
const scaleX = d3.scaleLinear()
.range([0,500])
.domain(d3.extent(values, (d)=>d.x));
const scaleY = d3.scaleLinear()
.range([480,20])
.domain([-5, 5]);
const line = d3.line()
.x(d => scaleX(d.x))
.y(d => scaleY(d.y));
d3.select('svg')
.selectAll('path')
.data([values])
.enter()
.append('path')
d3.select('svg')
.selectAll('line')
.data([-5,-4,-3,-2,-1,0,1,2,3,4,5])
.enter()
.append('line')
.attr('fill','none')
.attr('stroke',d=>{
if(d==0) return 'red';
return 'blue'
})
.attr('strke-width',2)
.attr('x1', scaleX(0))
.attr('x2', scaleX(scaleX.domain()[1]))
.attr('y1', d => scaleY(d))
.attr('y2', d => scaleY(d));
function update(){
d3.select('path')
.attr('fill','none')
.attr('stroke','black')
.attr('d', line);
}
update();
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment