block by shimizu 3c6e6f1d28ff6df52d0d60c80efa0b62

D3 v4 円の外周から外周にラインを引く

Full Screen

円の外周から外周にラインを引くのD3 ver.4版

Built with blockbuilder.org

index.html

<!DOCTYPE html>
<meta charset="utf-8">
<title>D3 v4 円の外周から外周にラインを引く</title>
<script src="//unpkg.com/babel-standalone@6.26.0/babel.min.js"></script>
<script src="//unpkg.com/d3@4.12.2/build/d3.min.js"></script>    
<style>
html, body {
    margin: 0px;
    height: 0px;
}

    
html, body, svg {
    width: 100%;
    height: 100%;
}
    
</style>

<body>

<svg id="stage"></svg>

<script type="text/babel">
const svg = d3.select("svg");
const w = document.querySelector("#stage").clientWidth;
const h = document.querySelector("#stage").clientHeight;
const r = Math.min(w,h) / 10;

const margin = r;

svg.selectAll("circle").data([[],[]]).enter().append("circle")
    .attr("cx", (d,i) => i * (r*4) + r)
    .attr("cy", r*2)
    .attr("fill", "none")
    .attr("stroke", "black")
    .attr("r", r)
    
svg.append("line").attr("stroke", "black")
    .attr("x1", r*2)
    .attr("y1", r*2)
    .attr("x2", r*4)
    .attr("y2", r*2)

setInterval(animation, 1000)

function animation(args) {
    //円1の中心座標
    const cx1 = Math.floor(Math.random() * (w-margin)) + margin;
    const cy1 = Math.floor(Math.random() * (h-margin)) + margin;
    
    //円2の中心座標
    const cx2 = Math.floor(Math.random() * (w-margin)) + margin;
    const cy2 = Math.floor(Math.random() * (h-margin)) + margin;
    
    //円を追加する
    const circle = svg.selectAll("circle").data([[cx1, cy1], [cx2, cy2]])
    circle
        .transition().duration(500)
        .attr("cx", d => d[0])
        .attr("cy", d=> d[1])
    
    //外周の座標を計算する    
    const cp = circuitsPoint(cx1, cy1, cx2, cy2, r)
    
    //円1の外周から、円2の外周までラインを引く    
    svg.select("line").transition().duration(500)
        .attr("x1", cx1 + cp.ox)
        .attr("y1", cy1 + cp.oy)
        .attr("x2", cx2 - cp.ox)
        .attr("y2", cy2 - cp.oy)
}




function circuitsPoint(cx1, cy1, cx2, cy2, r){
    const atan2 = Math.atan2(cy2 - cy1, cx2 - cx1);
    
    const ox = Math.cos(atan2) * r;
    const oy = Math.sin(atan2) * r;
    
    return { ox:ox, oy:oy }

}
    
</script>
</body>
</html>