Last active
March 23, 2017 07:44
-
-
Save Aleksey-Danchin/02d4e8d64897f9865454f0153d2b2987 to your computer and use it in GitHub Desktop.
(d3js) A Bézier curve https://codepen.io/al/full/VpxQRy/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const svg = d3.select("body").append('svg') | |
.attr('width', 500) | |
.attr('height', 500); | |
const data = [ | |
{cx: 10, cy: 10}, | |
{cx: 490, cy: 50}, | |
{cx: 50, cy: 490} | |
]; | |
const controlls = svg.selectAll('circle') | |
.data(data) | |
.enter().append('circle') | |
.attr('cx', d => d.cx) | |
.attr('cy', d => d.cy) | |
.attr('r', 5) | |
.call(d3.drag().on('drag', (d, i, l) => { | |
d3.select(l[i]) | |
.attr('cx', d3.event.x) | |
.attr('cy', d3.event.y); | |
update(); | |
})); | |
const path = svg.append('path') | |
.attr('fill-opacity', 0) | |
.attr('stroke', 'black') | |
.attr('stroke-width', 1); | |
const asymptote1 = svg.append('line').attr('stroke', 'black').attr('stroke-dasharray', [5, 5]) | |
, asymptote2 = svg.append('line').attr('stroke', 'black').attr('stroke-dasharray', [5, 5]); | |
const center = svg.append('circle') | |
.attr('r', 5) | |
.attr('fill', 'red'); | |
update(); | |
function update() { | |
const circles = controlls._groups[0]; | |
let dAttr = `M ${d3.select(circles[0]).attr('cx')} ${d3.select(circles[0]).attr('cy')} Q`; | |
for (let i = 1; i < circles.length; i++) { | |
dAttr += ` ${d3.select(circles[i]).attr('cx')} ${d3.select(circles[i]).attr('cy')}`; | |
} | |
path.attr('d', dAttr); | |
asymptote1.attr('x1', d3.select(circles[0]).attr('cx')); | |
asymptote1.attr('y1', d3.select(circles[0]).attr('cy')); | |
asymptote1.attr('x2', d3.select(circles[1]).attr('cx')); | |
asymptote1.attr('y2', d3.select(circles[1]).attr('cy')); | |
asymptote2.attr('x1', d3.select(circles[2]).attr('cx')); | |
asymptote2.attr('y1', d3.select(circles[2]).attr('cy')); | |
asymptote2.attr('x2', d3.select(circles[1]).attr('cx')); | |
asymptote2.attr('y2', d3.select(circles[1]).attr('cy')); | |
} | |
mark(); | |
function mark() { | |
center.transition() | |
.duration(3000) | |
.attrTween('transform', () => t => { | |
const pathElement = path.node() | |
, length = pathElement.getTotalLength() | |
, p = pathElement.getPointAtLength(t * length); | |
return `translate(${p.x}, ${p.y})`; | |
}) | |
.on("end", mark); | |
} | |
continues(); | |
function continues() { | |
path.transition() | |
.duration(3000) | |
.attrTween('stroke-dasharray', () => t => { | |
const pathElement = path.node() | |
, length = pathElement.getTotalLength(); | |
return d3.interpolateString("0," + length, length + "," + length)(t); | |
}) | |
.on("end", continues) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment