Published
Edited
Feb 23, 2021
1 star
Insert cell
Insert cell
{
const height = 60;
const context = DOM.context2d(width, height);

const drawAxis = await svg2canvas(context, svg =>
d3
.select(svg)
.append("g")
.attr("transform", "translate(0,36)")
.call(axis)
);

function draw(t) {
context.clearRect(0, 0, width, height);

// draw the background
context.globalAlpha = 0.4;
for (let i = 0; i < width; i += 3) {
context.fillStyle = d3.interpolateRainbow(i / width);
context.fillRect(i, 0, 3, height);
}

// draw the axis
drawAxis();

// draw the foreground
context.globalAlpha = 1;
context.strokeStyle = "white";
context.lineWidth = 3;
context.beginPath();
context.arc(x(t), 30, 25, 0, 2 * Math.PI);
context.stroke();
}

const ease1 = d3.easeBounceInOut,
ease2 = d3.easeCubic;
for (let t = 0; t < 1; t += .003) {
draw(.1 + ease1(t) - .4 * ease2(t));
yield context.canvas;
}

return context.canvas;
}
Insert cell
function svg2canvas(
ctx,
svgcallback,
ctxcallback = ctx => (ctx.globalAlpha = 1)
) {
const width = ctx.canvas.style.width
? parseFloat(ctx.canvas.style.width)
: ctx.canvas.width;
const height = width * (ctx.canvas.height / ctx.canvas.width);

return new Promise(async resolve => {
const s = document.createElementNS("http://www.w3.org/2000/svg", "svg");
s.setAttribute("viewBox", [0, 0, width, height]);
s.setAttribute("xmlns", "http://www.w3.org/2000/svg");
await svgcallback(s);

const i = new Image();
i.width = width;
i.height = height;
i.src = "data:image/svg+xml;utf8," + s.outerHTML;
const draw = () => {
ctx.save();
ctxcallback(ctx);
ctx.drawImage(i, 0, 0, i.width, i.height);
ctx.restore();
resolve(draw);
};
i.onload = draw;
});
}
Insert cell
x = d3.scaleLinear().range([20, width - 20])
Insert cell
axis = d3.axisTop(x)
Insert cell
d3 = require("d3@6")
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more