I attempted to create a matching pairs quiz using lines. I have several images on the left and several images on the right, and I want to connect them with lines when they are clicked. The connection should be flexible so that if image 1 on the left is connected to image 3 on the right, a line will appear connecting them. If I then click on image 1 on the right and image 2 on the left, the previous line should be deleted, and a new line between those two images should be created. Html snippet:
function lineDistance(x, y, x0, y0){
return Math.sqrt((x -= x0) * x + (y -= y0) * y);
};
function drawLine(a, b, line) {
var pointA = $(a ).offset();
var pointB = $(b).offset();
var pointAcenterX = $(a).width() / 2;
var pointAcenterY = $(a).height() / 2;
var pointBcenterX = $(b).width() / 2;
var pointBcenterY = $(b).height() / 2;
var angle = Math.atan2(pointB.top - pointA.top, pointB.left - pointA.left) * 180 / Math.PI;
var distance = lineDistance(pointA.left, pointA.top, pointB.left, pointB.top);
// Set Angle
$(line).css('transform', 'rotate(' + angle + 'deg)');
// Set Width
$(line).css('width', distance + 'px');
// Set Position
$(line).css('position', 'absolute');
if(pointB.left < pointA.left) {
$(line).offset({top: pointA.top + pointAcenterY, left: pointB.left + pointBcenterX});
} else {
$(line).offset({top: pointA.top + pointAcenterY, left: pointA.left + pointAcenterX});
}
}
new drawLine('.a', '.b', '.line');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="question">
<div id="old" class="left_side one_half svg left">
<a href="#" data-number="1"><img class="a" src="assets/svg/Kerze.svg"></a>
<a href="#" data-number="2"><img src="assets/svg/Telefon.svg"></a>
<a href="#" data-number="3"><img src="assets/svg/Schreibmaschine.svg"></a>
<a href="#" data-number="4"><img src="assets/svg/TV_old.svg"></a>
<a href="#" data-number="5"><img src="assets/svg/Zeitstopper.svg"></a>
<a href="#" data-number="6"><img src="assets/svg/Besen.svg"></a>
<a href="#" data-number="7"><img src="assets/svg/Waschen.svg"></a>
</div>
<div class="left_side one_half svg right">
<a href="#" data-letter="NS"><img src="assets/svg/Iwatch.svg"></a>
<a href="#" data-letter="RT"><img src="assets/svg/Laptop.svg"></a>
<a href="#" data-letter="TE"><img src="assets/svg/Staubsauger.svg"></a>
<a href="#" data-letter="IN"><img src="assets/svg/Waschmaschine.svg"></a>
<a href="#" data-letter="EI"><img src="assets/svg/TV_new.svg"></a>
<a href="#" data-letter="AL"><img src="assets/svg/Gluehbirne.svg"></a>
<a href="#" data-letter="BE"><img class="b" src="assets/svg/Iphone.svg"></a>
<div class="line"></div>
</div>
</div>
I have successfully created a line between two images (from class a to class b), which is always calculated to form a right angle. However, I am struggling to implement the functionality as described above. Any suggestions? Thank you.