Cosine Curve
Math
Code
= {
chart const margin = { top: 20, right: 10, bottom: 20, left: 10 };
const width = fullWidth - margin.left - margin.right,
= fullHeight - margin.top - margin.bottom;
height
const window = d3.create("svg")
.attr("width", "100%")
.attr("height", "100%")
.attr("viewBox", `0 0 ${fullWidth} ${fullHeight}`)
.attr("preserveAspectRatio", "xMidYMid meet");
const svg = window.append("g")
.attr("class", "cosine")
.attr("transform", `translate(${margin.left},${margin.top})`);
const xmin = -1.2,
= 6.4,
xmax = -(height / width) * (xmax - xmin) / 2,
ymin = -ymin;
ymax
const x = d3.scaleLinear().domain([xmin, xmax]).range([0, width]),
= d3.scaleLinear().domain([ymin, ymax]).range([height, 0]);
y
.append("path")
svg.attr("class", "axis")
.attr("d", `M${x(xmin)},${y(0)}H${width},${y(0)}`);
.append("path")
svg.attr("class", "axis")
.attr("d", `M${x(0)},${y(ymin)}V${x(0)},${y(ymax)}`);
.append("circle")
svg.attr("class", "axis")
.attr("cx", x(0))
.attr("cy", y(0))
.attr("r", x(1) - x(0));
let p = 0;
const dp = 0.01;
const line = d3.line()
.x(d => x(d))
.y(d => y(Math.cos(d - p)))
.curve(d3.curveBasis);
const arc = d3.arc()
.innerRadius(0)
.outerRadius(x(1) - x(0))
.startAngle(0);
.append("path")
svg.datum({ endAngle: p })
.attr("class", "wedge")
.attr("transform", `translate(${x(0)},${y(0)})`)
.attr("d", arc);
.append("line")
svg.attr("class", "line line-0");
.append("path")
svg.datum(d3.range(0, xmax, dp * xmax))
.attr("class", "line line-1")
.attr("d", line);
.append("line")
svg.attr("class", "line line-2")
.attr("x1", x(0))
.attr("x2", x(0))
.attr("y1", y(1))
.attr("y2", y(1));
.selectAll(".circle")
svg.data(d3.range(2))
.join("circle")
.attr("class", "circle")
.attr("cx", x(0))
.attr("cy", y(1))
.attr("r", 5);
function tick() {
+= dp;
p if (p > 2 * Math.PI - 0.5 * dp){
= 0;
p
}
.select(".wedge")
svg.datum({ endAngle: p })
.attr("d", arc);
.selectAll(".line-0")
svg.attr("x1", x(Math.sin(p)))
.attr("y1", y(Math.cos(p)))
.attr("x2", x(0))
.attr("y2", y(Math.cos(p)));
.select(".line-1")
svg.attr("d", line);
.select(".line-2")
svg.attr("x2", x(p));
.selectAll(".circle")
svg.each(function(d) {
switch (d) {
case 0:
.select(this)
d3.attr("cx", x(Math.sin(p)))
.attr("cy", y(Math.cos(p)));
break;
case 1:
.select(this)
d3.attr("cx", x(p));
break;
};
})
}
const timer = d3.interval(tick, 20);
.then(() => {
invalidation.stop();
timer;
})
return window.node();
}
This animation demonstrates the relationship of \(\cos(x)\) to the circle.