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

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