Published unlisted
Edited
Jul 18, 2022
Insert cell
# Replicating CSS animation in d3
Insert cell
{
const width = 1280;
const height = 720;
const svgns = 'http://www.w3.org/2000/svg';
const svg = d3
.create("svg")
.attr('xmlns', svgns)
.attr('viewBox', `0 0 ${width} ${height}`);

svg.append('rect')
.attr('class', 'vBoxRect')
.attr('width', `${width}`)
.attr('height', `${height}`)
.attr('fill', '#EFEFEF')
/*green circle on the right with css animation*/
const circ = svg.append('circle')
.attr('class', 'circ2')
.attr('cx', '850')
.attr('cy', '360')
.attr('r', '50')
.attr('stroke', 'green')

const style =
d3.select('body')
.append('style')
.attr('type', 'text/css')

const keyFrame = `
.circ2 {
fill-opacity: 0;
transform-box: fill-box;
transform-origin: center;
animation-duration: 2s;
animation-name: pulse;
animation-iteration-count: infinite;
}

@keyframes pulse {
from {
stroke-width: 4;
stroke-opacity: 1;
transform: scale(0.3);
}
to {
stroke-width: 0;
stroke-opacity: 0;
transform: scale(2);
}
}
`
style['_groups'][0][0].innerHTML = keyFrame;

/*red circle on the left with d3 animation*/

function circleTransition() {
const circ1 = svg.append('circle')
.attr('class', 'circ1')
.attr('cx', '640')
.attr('cy', '360')
.attr('r', '50')
.attr('stroke', 'red')

repeat();

function repeat() {
circ1
.style('fill-opacity', '0')
.style('transform-box', 'fill-box')
.style('transform-origin', 'center')
.style('stroke-width', '4')
.style('stroke-opacity', '1')
.style('transform', 'scale(0.3)')
.transition()
.duration(2000)
.ease(d3.easeCubicOut)
.style('stroke-width', '0')
.style('stroke-opacity', '0')
.style('transform', 'scale(2)')
.on('end', repeat)
};
};
circleTransition();
return svg.node();
}
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