You can use lineTo from the canvas context. See https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D for more details.
First you define the canvas in html:
<canvas id="connection-canvas"></canvas>
Then you can draw a line on it:
function drawLine(p1, p2) { var canvas = document.getElementById("connection-canvas"); var ctx = canvas.getContext("2d"); ctx.beginPath(); ctx.moveTo(p1.x, p1.y); ctx.lineTo(p2.x, p2.y); ctx.stroke(); }
All you need to do is figure out the offset of your circular pointers:
function getPoint(answerElement) { var roundPointer = answerElement.lastElementChild; return { y: answerElement.offsetTop + roundPointer.offsetTop + roundPointer.offsetHeight / 2, x: answerElement.offsetLeft + roundPointer.offsetLeft + roundPointer.offsetWidth / 2 }; }
Thus, you can use these two functions to get the center point of the “circular pointer” and draw a line in the canvas from it to the other “circular pointer”, assuming that the canvas is located on the same parent offset container and its size should be big enough.
Then you will need to select two answers to connect them. Below is a demo. This demo does not handle erasing a line if you change the answer.
var lastSelection;
.padding-answer-line-mapping { padding-bottom:8px; } .answer-container { width:40px; height:40px; background-color:#ccc; border:1px solid #ccc; margin:2px; float:left; text-align:center; padding-top:8px; cursor:pointer; position:relative; } .answer-container:hover, .answer-container:focus, .answer-container:active { background-color: #0076e9; color: white; border: 1px solid #0076e9; } .round-pointer-right { position: absolute; background-color:#ccc; cursor:pointer; width:10px; height:10px; border-radius: 50%; right:0px; top:14px; margin-right:-20px; } .round-pointer-left { position: absolute; background-color:#ccc; cursor:pointer; width:10px; height:10px; border-radius: 50%; left:0px; top:14px; margin-left:-20px; } .selected { background-color: red; }
<link href="//code.ionicframework.com/1.3.1/css/ionic.css" rel="stylesheet"/> Match the following items. <canvas id="connection-canvas" style="position: absolute; top: 0; left: 0; right: 0; bottom: 0"></canvas> <div class="row padding-answer-line-mapping"> <div class="col answer-container"> One <div class="round-pointer-right"></div> </div> <div class="col"> </div> <div class="col answer-container"> 2 <div class="round-pointer-left"></div> </div> </div> <div class="row padding-answer-line-mapping"> <div class="col answer-container"> Two <div class="round-pointer-right"></div> </div> <div class="col"> </div> <div class="col answer-container"> 1 <div class="round-pointer-left"></div> </div> </div>
source share