연말이라서 공부가 하기 싫어서 Circle 움직임만 계속 만들어 실험하고 놀고 있네요. 오늘은 Circle 마지막 시간으로 특정 경로 이동하는 움직임을 만들어 Circle을 이동 시킨 후 특정 위치에서 소멸되게 하는 실험을 간단히 하겠습니다.
[실험 기본소스]
<body>
<script src="https://d3js.org/d3.v5.min.js"></script>
<script>
var canvas = d3.select("body").append("svg")
.attr("width",500)
.attr("height",500)
.style("background-color","yellow")
.on("click", circleDrawing);
function circleDrawing() {
var mouseXY = d3.mouse(this);
var circle = canvas.append("circle")
.attr("cx",mouseXY[0]) //시작위치
.attr("cy",mouseXY[1])
.attr("r",10)
.attr("fill", d3.hsl((Math.random()*1000 % 360), 1, 0.5))
.transition()
.duration(3000)
.ease(Math.sqrt)
.attr("cx",500/2)
.attr("cy",500/2)
.attr("r", 100)
.remove();
}
</script>
</body>
우선 이동 패턴을 만들어야 합니다. 처음 중심좌표로 이동은 기존 실험 소스대로 이동은 그대로 둡니다.
두번째 대각선 이동은 다음과 같습니다.
.transition()
.duration(2000)
.ease(Math.sqrt)
.attr("cx",480)
.attr("cy",20)
캔버스 왼쪽 상단으로 이동한 뒤에서 캔버스 테두리를 한바퀴 돌아야 합니다. 한바퀴 돌기 위해서는 cxy, cy의 각 캔버스 꼭지점의 좌표를 transition()함수로 지정해주면 됩니다.
다음과 같이 지정해주면 됩니다.
[1단계] : 캔버스 오른쪽 상단 꼭지점
.attr("cx",480)
.attr("cy",20)
[2단계] : 캔버스 오른쪽 하단 꼭지점
.attr("cx",480)
.attr("cy",480)
[3단계] : 캔버스 왼쪽 하단 꼭지점
.attr("cx",20)
.attr("cy",480)
[4단계] : 캔버스 왼쪽 상단 꼭지점
.attr("cx",20)
.attr("cy",20)
[5단계] : 캔버스 중심 상단 꼭지점
.attr("cx",250)
.attr("cy",20)
[6단계] : 소멸 지점
.attr("cx",250)
.attr("cy",100)
<body>
<script src="https://d3js.org/d3.v5.min.js"></script>
<script>
var canvas = d3.select("body").append("svg")
.attr("width",500)
.attr("height",500)
.style("background-color","yellow")
.on("click", circleDrawing);
var rect = canvas.append("rect")
.attr("x","220")
.attr("y","70")
.attr("width","60")
.attr("height","60")
.attr("fill", "blue") //내부색
.attr("stroke","red") //테두리색
.attr("stroke-width","5") //테두리 두께
.attr("opacity","0.5"); //불투명도
function circleDrawing() {
var mouseXY = d3.mouse(this);
var circle = canvas.append("circle")
.attr("cx",mouseXY[0]) //시작위치
.attr("cy",mouseXY[1])
.attr("r",5)
.attr("fill", d3.hsl((Math.random()*1000 % 360), 1, 0.5))
.transition()
.duration(2000)
.ease(Math.sqrt)
.attr("cx",250)
.attr("cy",250)
.attr("r", 20)
.transition()
.duration(2000)
.ease(Math.sqrt)
.attr("cx",480)
.attr("cy",20)
.transition()
.duration(2000)
.ease(Math.sqrt)
.attr("cx",480)
.attr("cy",480)
.transition()
.duration(2000)
.ease(Math.sqrt)
.attr("cx",20)
.attr("cy",480)
.transition()
.duration(2000)
.ease(Math.sqrt)
.attr("cx",20)
.attr("cy",20)
.transition()
.duration(2000)
.ease(Math.sqrt)
.attr("cx",250)
.attr("cy",20)
.transition()
.duration(2000)
.ease(Math.sqrt)
.attr("cx",250)
.attr("cy",100)
.remove();
}
</script>
</body>
[결과]
일부러 loop문을 안만들고 패턴을 배열변수에 cx, cy 좌표를 저장 안했네요. 그 이유는 직접적으로 transition()함수의 동작을 어떻게 수행되는지 볼 수 있게 하기 위해서 입니다. 원래는 transtion()함수 이하의 몇개의 함수들이 계속 반복되는데 이 걸 묶어서 패턴값인 cx, cy의 좌표를 배열변수로 지정해서 루프를 돌리면 코딩은 대폭 줄어 듭니다. 한번 시도해보세요.
위 실험을 한 코딩을 그대로 따라 해도 되지만 움직임을 다르게 한번 좌표를 잡고 Circle의 움직임을 만들어 보세요. 아마 재미 있을 거에요.