Draw arrow between lists - Javascript Canvas

Javascript examples for Canvas:Draw

Description

Draw arrow between lists

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="https://code.jquery.com/jquery-1.4.4.min.js"></script> 
      <style id="compiled-css" type="text/css">

.listholder {//from ww w  .j a  va 2  s  .  c o m
   position: relative;
}
.highlight {
   background-color: #f88;/**/
}
#arrowholder {
   position: relative;
}
#arrow {
   position: absolute;
   pointer-events: none;
}
.list1 {
   float: left;
   width: 150px;
   margin-right: 40px;
}
.list2 {
   float: left;
   width: 150px;
}


      </style> 
      <script type="text/javascript">
    $(window).load(function(){
var arrow=$("#arrow");
var ctx=arrow.get(0).getContext("2d");
arrow.get(0).height=$(".list1").height();
function getPos(elem, end) {
    var temp=elem;
    if(end) {
        temp=$("<span>x</span>").appendTo(elem);
    }
    var position=temp.position();
    if(end) {
        temp.remove();
    }
    return position;
}
$(".list1 li, .list2 li").hover(function () {
    var n = this.id.substr(2);
    $("#qq" + n + ", #aa" + n).toggleClass("highlight");
});
$(".list1 li, .list2 li").hover(function() {
    var xOffset=10;
    var yOffset=9;
    var id=this.id.substr(2);
    var pos1=getPos($("#qq"+id), true);
    var pos2=getPos($("#aa"+id), false);
    pos1.left+=xOffset;
    pos2.left-=xOffset;
    pos1.top+=yOffset;
    pos2.top+=yOffset;
    ctx.beginPath();
    ctx.moveTo(pos1.left, pos1.top);
    ctx.lineTo(pos2.left, pos2.top);
    ctx.strokeStyle="#f00";
    ctx.lineWidth=2;
    ctx.stroke();
    ctx.save();
    ctx.translate(pos2.left, pos2.top);
    ctx.rotate(Math.atan2(pos2.top-pos1.top, pos2.left-pos1.left));
    ctx.beginPath();
    ctx.moveTo(0, -5);
    ctx.lineTo(8, 0);
    ctx.lineTo(0, 5);
    ctx.closePath();
    ctx.fillStyle="red";
    ctx.fill();
    ctx.restore();
}, function() {
    ctx.clearRect(0, 0, arrow.width(), arrow.height());
});
    });

      </script> 
   </head> 
   <body> 
      <div class="listholder"> 
         <div id="arrowholder"> 
            <canvas id="arrow" width="300" height="200"></canvas> 
         </div> 
         <ul class="list1"> 
            <li id="qq1">sdfsdv</li> 
            <li id="qq2">bnvnvb</li> 
            <li id="qq3">nmnutymnj7</li> 
            <li id="qq4">cvbc</li> 
            <li id="qq5">45tsgd</li> 
         </ul> 
         <ul class="list2"> 
            <li id="aa3">fgtbrtgb</li> 
            <li id="aa1">vbn xgbn</li> 
            <li id="aa5">vdgver</li> 
            <li id="aa4">asdasdv</li> 
            <li id="aa2">nvfbnfn</li> 
         </ul> 
      </div>  
   </body>
</html>

Related Tutorials