表示されないときはリロードしてください。
Built with blockbuilder.org
表示されないときはリロードしてください。
Built with blockbuilder.org
<!DOCTYPE html> | |
<meta charset="utf-8"> | |
<title>円の外周から外周にラインを引く</title> | |
<script src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/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> | |
var svg = d3.select("svg"); | |
var w = document.querySelector("#stage").clientWidth; | |
var h = document.querySelector("#stage").clientHeight; | |
var r = Math.min(w,h) / 10; | |
var margin = r; | |
svg.selectAll("circle").data([[],[]]).enter().append("circle").attr({ | |
"fill":"none", | |
"stroke":"black", | |
"r":r | |
}); | |
svg.append("line").attr("stroke", "black") | |
setInterval(animation, 1000) | |
function animation(args) { | |
//円1の中心座標 | |
var cx1 = Math.floor(Math.random() * (w-margin)) + margin; | |
var cy1 = Math.floor(Math.random() * (h-margin)) + margin; | |
//円2の中心座標 | |
var cx2 = Math.floor(Math.random() * (w-margin)) + margin; | |
var cy2 = Math.floor(Math.random() * (h-margin)) + margin; | |
//円を追加する | |
var circle = svg.selectAll("circle").data([[cx1, cy1], [cx2, cy2]]) | |
circle.transition().duration(500) | |
.attr({ | |
"cx":function(d){ return d[0] }, | |
"cy":function(d){ return d[1] } | |
}); | |
//外周の座標を計算する | |
var cp = circuitsPoint(cx1, cy1, cx2, cy2, r) | |
//円1の外周から、円2の外周までラインを引く | |
svg.select("line").transition().duration(500) | |
.attr({ | |
"x1": cx1 + cp.ox , | |
"y1": cy1 + cp.oy, | |
"x2": cx2 - cp.ox, | |
"y2": cy2 - cp.oy, | |
"stroke": "black" | |
}) | |
} | |
function circuitsPoint(cx1, cy1, cx2, cy2, r){ | |
var atan2 = Math.atan2(cy2 - cy1, cx2 - cx1); | |
var ox = Math.cos(atan2) * r; | |
var oy = Math.sin(atan2) * r; | |
return { ox:ox, oy:oy } | |
} | |
</script> | |
</body> | |
</html> |