[D3.js] d3.on() 함수

in #dclick6 years ago (edited)

[D3.js] d3.on() 함수


d3.on()함수에 대해서 이야기가 하고 싶어 오늘의 주제로 결정 했습니다. 지난시간에 드래그 함수 편에서 이 함수를 사용하여 Circle(원) 이미지를 캔버스 영역에서 자유자재로 이동을 시켰습니다. 그때 사용한 type은 "start", "drag", "end" 등을 이용하여 실험 했는데 추가로 d3 예제 중 "mouseover", "mouseout" type을 이용한 예제를 발견했는데 이번에 5개의 type을 정리해 보면 좋을 것 같아서 한편의 post로 작성해 봅니다.

1. d3.on() 함수


  • .on(type,동작함수) : type에 따라 각 동작을 수행하게 됩니다.

우선 D3.js에서 제가 알고 있는 타입은 "start", "drag", "end", "mouseover", "mouseout" 등을 알고 있네요.

  • start : 해당 객체를 특정한 동작을 수행하기 전 제일 먼저 이벤트 발생
  • drag : 마우스로 드래그 할 때 이벤트 발생
  • end : 해당 객체를 특정 동작을 수행 한 후 끝날 때 이벤트 발생
  • mouseover : 마우스가 해당 객체영역 안에 들어 갈 때 이벤트 발생
  • mouseout : 마우스가 해당 객체영역 밖으로 나갈 때 이벤트 발생

잘 연상이 안되는 분들도 있을 거에요. 좀 더 쉽게 살펴보도록 하죠.

2. d3.on()함수의 type 별 동작 예제


1) "start", "drag", "end" 동작 예제



이 동작은 링크 된 참조 post를 보시면 됩니다. 다시 전부 거론하기 그래서 해당 코딩 부분만 줄여서 살펴보면 다음과 같습니다.

.call(d3.drag()
               .on("start", function(d){d3.select(this).raise().classed("active", true);})
               .on("drag", function(d) {d3.select(this).attr("cx", d.x = d3.event.x).attr("cy", d.y = d3.event.y);})
               .on("end",  function(d) {d3.select(this).classed("active", false);}));

해당 객체가 call()함수로 drag()함수가 호출되면 3가지 동작을 수행합니다. 호출과 동시에 on("start", 동작)가 제일 먼저 이벤트가 발생하고 그다음 on("drag",동작) 이벤트가 발생합니다. 다 수행 한 후 끝날 때 on("end",동작)이 제일 마지막 이벤트가 발생으로 해당 객체의 동작이 끝나게 됩니다.

2) "start", "end" 동작 예제


이번 동작은 해당 객체가 특정 동작을 수행할 때 시작과 끝날때 이벤트가 발생하는 예제입니다.

<body>
  <script src="https://d3js.org/d3.v5.min.js"></script>
  <script>
 
    var canvas = d3.select("body").append("svg")
         .attr("width",500)
         .attr("height",100)
         .style("background-color","yellow");

    var circle = canvas.append("circle")
         .attr("cx",50) //시작위치
         .attr("cy",50)
         .attr("r",25);
        
        //circle(원)을 움직이게 동작
    circle.transition()
         .duration(2000) //동작시간
         .delay(1000) //지연시간
         .attr("cx",450) //이동거리
           .on("start",function(){d3.select(this).attr("fill","red");})
           .on("end",function(){d3.select(this).attr("fill","blue");}); 
  </script> 
</body>

circle(원)을 움직이게 하는 동작 코딩에서 이 circle(원) 객체가 cx가 50인 시작위치에서 450인 위치로 이동하기를 수행하기 전 먼저 circle(원)을 red 색으로 지정하고 이동이 끝나는 시점에 circle(원)을 blue로 지정하게 됩니다. 뭔가를 특정 동작을 수행하기 전과 수행 한 후 끝날 때 이벤트가 발생합니다.

그 결과를 살펴 볼까요.

3) "mouseover", "mouseout" 동작 예제


이 동작은 마우스가 해당 객체 영역 안으로 들어가면 "mousover" 이벤트가 발생하고 해당 객체 영역 밖으로 나가면 "mouseout" 이벤트가 발생합니다.

그러면, 간단히 어떻게 동작하는지 코딩해 보죠.

<body>
  <script src="https://d3js.org/d3.v5.min.js"></script>
  <script>
 
    var canvas = d3.select("body").append("svg")
         .attr("width",500)
         .attr("height",100)
         .style("background-color","yellow");

    var circle = canvas.append("circle")
         .attr("cx",50) //시작위치
         .attr("cy",50)
         .attr("r",25)  
         .attr("fill","blue")
          .on("mouseover",function(){d3.select(this).attr("fill","red");})
          .on("mouseout",function(){d3.select(this).attr("fill","blue");});
</body>

위 코딩을 보면 circle(원)을 그릴 때 on()함수 두개로 "mouseover", "mouseout" 만 설정해 주면 됩니다. 해당 circle(원)에 대해 마우스가 원 안으로 들어오면 red 색으로 원 밖으로 나가면 blue 색으로 설정한다는 조건만 코딩하면 끝납니다.

결과는 다음과 같습니다.

3. 종합 실험 코딩



마지막으로 5개를 전부 적용한 예제를 코딩을 해보겠습니다. post [D3.js] 드래그(d3.drag()) 함수 편이 3개의 type인 "start", "drag", "end" 등이 있기 때문에 나무지 "mouseover", "mouseout" type만 추가하여 5개를 모두 적용한 예제를 만들어 보죠.

[참조소스 일부분] : circle(원)을 드래그해서 이동시키는데 이때 마우스가 circle(원)을 드래그 할 때 circle(원)의 영역으로 마우스가 들어가게 되고 드래그가 끝나면 circle(원)의 영역 밖으로 나가게 됩니다. 이때 "mouseover", "mouseout" 이벤트 발생시키면 좋겠죠.

    //데이터 출력
    function render(dataset){
      var circle = svg.selectAll("circle").data(dataset)
            .enter().append("circle")
             .attr("cx",function(d){return d.x;})
             .attr("cy",function(d){return d.y;})
             .attr("r",function(d){return rScale(d.r);})
             .attr("fill",function(d){return ColorScale(d.r);})
             .call(d3.drag()
               .on("start", function(d){d3.select(this).raise().classed("active", true);})
               .on("drag", function(d) {d3.select(this).attr("cx", d.x = d3.event.x).attr("cy", d.y = d3.event.y);})
               .on("end",  function(d) {d3.select(this).classed("active", false);}))
               .on('mouseover',function(){d3.select(this).attr("fill","red");})
               .on('mouseout',function(){d3.select(this).attr("fill",function(d){return ColorScale(d.r);})})
    }

보는 것 같이 마우스가 circle(원) 안으로 들어가면 red 색으로 바뀌고 circle(원) 밖으로 나가게 되면 기존 원래의 색 ColorScale(d.r) 값으로 되돌아가게 됩니다.

[종합소스]

<script src="https://d3js.org/d3.v5.min.js"></script>
<body>
  <script>
    var rScale = d3.scaleLinear().domain([0,10]).range([0,50]);
    var ColorScale = d3.scaleLinear().domain([0,10]).range(["red","blue"]);

    //배경
    var svg = d3.select("body").append("svg")
          .attr("width",500)
          .attr("height",500)
          .style("background-color","yellow");
                    
    //데이터 출력
    function render(dataset){
      var circle = svg.selectAll("circle").data(dataset)
            .enter().append("circle")
             .attr("cx",function(d){return d.x;})
             .attr("cy",function(d){return d.y;})
             .attr("r",function(d){return rScale(d.r);})
             .attr("fill",function(d){return ColorScale(d.r);})
             .call(d3.drag()
               .on("start", function(d){d3.select(this).raise().classed("active", true);})
               .on("drag", function(d) {d3.select(this).attr("cx", d.x = d3.event.x).attr("cy", d.y = d3.event.y);})
               .on("end",  function(d) {d3.select(this).classed("active", false);}))
               .on('mouseover',function(){d3.select(this).attr("fill","red");})
               .on('mouseout',function(){d3.select(this).attr("fill",function(d){return ColorScale(d.r);})})

    }
        
    //데이터 읽기
    d3.csv("data.csv",type).then(function(data){      
         render(data);
    });
        
    //데이터 타입
    function type(d){
      d.x=+d.x;  //parseFloat(d.x);
      d.y=+d.y;  //parseFloat(d.y);
      return d;
    }
  </script>
</body> 

[결과]

마무리


이렇게 해서 on()함수에 대해서 간단히 살펴 보았습니다. 굳이 이렇게 개별적으로 예제를 만들어서 post한 이유는 각각 느낌을 이해 하시라는 의도가 담겨 있습니다. 개별적 동작 느낌을 이해하시면 어떤식으로 마지막 예제처럼 전부 합쳐서 하나의 표현을 할 수도 있습니다. 각 개별적 동작 느낌을 제대로 이해 했을 때 각 type을 자유자재로 활용 할 수 있습니다.

참고로 이외에 다른 type이 있는지 한번 찾아보세요.



Sponsored ( Powered by dclick )
[Tasteem][테이스팀 검증단] 검증이 필요없다!! 최고의 맛집!! 마산 오시면 대접해 드리겠습니다. 마산 밋업 가즈아~ 호야 메기 매운탕을 소개합니다.

안녕하세요. 굳헬로 @goodhello 입니다. 테이스팀에 검색 기능이 추가되면서 재미난 주제...

logo

이 글은 스팀 기반 광고 플랫폼
dclick 에 의해 작성 되었습니다.

Sort:  

Congratulations @codingman! You have completed the following achievement on the Steem blockchain and have been rewarded with new badge(s) :

Award for the number of upvotes received

Click on the badge to view your Board of Honor.
If you no longer want to receive notifications, reply to this comment with the word STOP

Do not miss the last post from @steemitboard:

SteemitBoard Ranking update - Steem Power, Followers and Following added

Support SteemitBoard's project! Vote for its witness and get one more award!

ㅎ 저 폰으로 디클릭 클릭했는데 혹 카운팅 되는지 봐주실래요?
방금요

모르겠네요.
안된 것 같기도 하고 된 것 같기도 하고요.

마우스로 만든 원을 끌고 가는 것도 가능하네요. 신기해요.

이 함수가 참 재미 있지요.
이외 다른 type도 있는데 더 재미 있는 것 같아요.

디클하구 가여.
코딩의 신비~ 간단한데도 저런거 몇개면 원시 게임하나 만들거같아여

d3 게임 찾아보세요
은근 재밌는 게임을 찾을 수 있을 거에요.

Coin Marketplace

STEEM 0.18
TRX 0.15
JST 0.030
BTC 58776.30
ETH 2576.56
USDT 1.00
SBD 2.44