Public
Edited
Jun 5
Fork of Untitled
Insert cell
viewof sineWave = {
const width = 1200;
const height = 300;

// --- Controls ---
const controls = document.createElement("div");

const ampInput = Object.assign(document.createElement("input"), {
type: "range",
min: 0.1,
max: 2,
step: 0.01,
value: 1
});
const waveInput = Object.assign(document.createElement("input"), {
type: "range",
min: 0.1,
max: 4,
step: 0.01,
value: 1
});

const ampLabel = document.createElement("label");
ampLabel.textContent = "Amplitude: ";
ampLabel.append(ampInput);

const waveLabel = document.createElement("label");
waveLabel.textContent = "Wavelength: ";
waveLabel.append(waveInput);

controls.append(ampLabel, document.createElement("br"), waveLabel);

const svg = d3.select(DOM.svg(width, height))
.style("border", "1px solid #ccc");

const xScale = d3.scaleLinear()
.domain([0, 10 * Math.PI])
.range([0, width]);

const yScale = d3.scaleLinear()
.domain([-2.2, 2.2])
.range([height, 0]);

const lineGen = d3.line()
.x(d => xScale(d.x))
.y(d => yScale(d.y));

const path = svg.append("path")
.attr("stroke", "steelblue")
.attr("stroke-width", 2)
.attr("fill", "none");

function update() {
const amplitude = parseFloat(ampInput.value);
const wavelength = parseFloat(waveInput.value);

const data = [];
const step = 0.1;
for (let x = 0; x <= 10 * Math.PI; x += step) {
data.push({ x, y: amplitude * Math.sin(x * wavelength) });
}

path.datum(data).attr("d", lineGen);
}

ampInput.oninput = waveInput.oninput = update;
update(); // Initial draw

const container = document.createElement("div");
container.append(controls, svg.node());
return container;
}

Insert cell
md`# Light waves`
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
html`
<style>
.rect {
width: 200px;
height: 20px;
background: hsl(${hue}, 100%, 50%);
margin: 10px;
padding: 0 calc(1/${hue})px;
}
</style>
<p>${hue}<sup>o</sup></p>
<div class="rect"></div>
<div class="rect"></div>
`
Insert cell
Insert cell
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more