Linking pictures with strokes

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.

Answer №1

let setLeft = false, setRight = false;
$('.leftSide img').click(function(){
    $('.leftSide img').removeClass('a');
    $(this).addClass('a');
  setLeft = true;
  new drawLine('.a', '.b', '.line');
});
$('.rightSide img').click(function(){
    $('.rightSide img').removeClass('b');
    $(this).addClass('b');
  setRight = true;
  new drawLine('.a', '.b', '.line');
});

To track the clicks on images from left and right side, we can use flag variables. When an image from the right is clicked, set the right flag variable to be true, and do the same for the left.

Within the drawLine function, check if both flag variables are true before drawing a line between a and b. After drawing the line, reset the flag variables to false.

function lineDistance(x, y, x0, y0){
    return Math.sqrt((x -= x0) * x + (y -= y0) * y);
};

function drawLine(a, b, line) {

if(setLeft && setRight){
  setLeft = false;
    setRight = false;
    var pointA = $(a).offset();
    var pointB = $(b).offset();
    console.log(pointA);
    console.log(pointB);
    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');
let setLeft = false, setRight = false;
$('.leftSide img').click(function(){
$('.leftSide img').removeClass('a');
$(this).addClass('a');
  setLeft = true;
  new drawLine('.a', '.b', '.line');
});
$('.rightSide img').click(function(){
$('.rightSide img').removeClass('b');
$(this).addClass('b');
  setRight = true;
  new drawLine('.a', '.b', '.line');
});
.left{
  float:left;
}
.right{
  float:right;
}
.one_half{
  width:40%;
}
img{
  max-width:100%;
}
.line{
  background: red;
  height:1px;
}
.question{
  position: relative;
  overflow: hidden;
}
<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 leftSide">
    <a href="#" data-number="1"><img src="https://www.w3schools.com/css/trolltunga.jpg"></a>
    <a href="#" data-number="2"><img src="https://www.w3schools.com/css/trolltunga.jpg"></a>
    <a href="#" data-number="3"><img src="https://www.w3schools.com/css/trolltunga.jpg"></a>
    <a href="#" data-number="4"><img src="https://www.w3schools.com/css/trolltunga.jpg"></a>
    <a href="#" data-number="5"><img src="https://www.w3schools.com/css/trolltunga.jpg"></a>
    <a href="#" data-number="6"><img src="https://www.w3schools.com/css/trolltunga.jpg"></a>
    <a href="#" data-number="7"><img src="https://www.w3schools.com/css/trolltunga.jpg"></a>
  </div>
  <div class="left_side one_half svg right rightSide">
    <a href="#" data-letter="NS"><img src="https://www.w3schools.com/css/trolltunga.jpg"></a>
    <a href="#" data-letter="RT"><img src="https://www.w3schools.com/css/trolltunga.jpg"></a>
    <a href="#" data-letter="TE"><img src="https://www.w3schools.com/css/trolltunga.jpg"></a>
    <a href="#" data-letter="IN"><img src="https://www.w3schools.com/css/trolltunga.jpg"></a>
    <a href="#" data-letter="EI"><img src="https://www.w3schools.com/css/trolltunga.jpg"></a>
    <a href="#" data-letter="AL"><img src="https://www.w3schools.com/css/trolltunga.jpg"></a>
    <a href="#" data-letter="BE"><img src="https://www.w3schools.com/css/trolltunga.jpg"></a>
    <div class="line"></div>  
  </div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Achieve an overlapping effect with grid items

I'm in the process of creating a CSS grid layout where the header overlaps the next row. Below is a snippet of my code with the header positioned on top, and the linked image should give you an idea of what I'm aiming for. Thank you! https://i ...

What is the process of converting an image taken with the 'react-camera-pro' into a byte array?

I am in the process of capturing an image using a camera through 'react-camera-pro' and I need to figure out how to convert the captured image into a byte array. Here is the snippet of code that I am working with: const camera = useRef(null); ...

Finding the optimal image prediction from HTML using Google JSoup - A guide

Our goal is to accurately identify the best guess for an image based on the HTML content of the search results page returned by Google. Among the various classes present, we know that the best guess is associated with the class qb-b. To target this specifi ...

Transforming JavaScript date into JSON date structure

Currently, I am integrating an API that requires the JSON date format. My task involves converting a JavaScript date Sat Jan 17 1970 07:28:19 GMT+0100 (Romance Standard Time) into the JSON date format: /Date(1405699200)/ ...

Adjusting the Style of a Parent Element Depending on the Content of its Child Element

I'm currently working on changing the visibility of the second div that has the class .form-group. I'm using jQuery to get the selected option value and then adjust the visibility based on that value. If the value is 0, then the second div .form ...

Struggling with Creating Custom Validation Methods in JQuery

I'm currently implementing the JQuery validation plugin and have created a new method to check the availability of a name in the database. The PHP script is functioning properly, returning either 1 or 0 depending on availability. However, the method c ...

Customizing window.alert to accept more than one argument

I am wondering about customizing the window.alert function in order to pass multiple parameters. Can anyone offer an explanation as to why the for/in loop inherits the body of Array.prototype.tester into the list array? Your insight is greatly appreciate ...

Challenges in Ensuring Proper Alignment of Connection Line Between Boxes on Left and Right Sides within a React Component

Currently, I am developing a React component that displays two sets of boxes on the left and right sides of the screen. Users can choose one box from each side and click a "Connect" button to draw a line between them. However, I am encountering an issue wh ...

experiencing a never-ending loop while attempting to load images through ajax requests

I am attempting to ensure that user uploaded files remain private in node.js. I am utilizing angular to display the file on the client side. <div ng-repeat="message in messages"> <div class="details" ng-if="message.type == 'photo'"& ...

Coloring the entire table as a whole instead of individual cells

I'm struggling with formatting a table that displays roles as "EXISTS" or "MISSING". The issue is that the code I found online to color code the cells is coloring the entire table green, not just the cells with "EXISTS". I'm not very familiar wit ...

Using Google App Script to transfer specific columns of a row to a different tab based on the value in a particular column

I have a script that moves rows based on a specific value in a column, but I am looking to only transfer certain columns within those rows. This is the current script I am using: //Script to move rows from Form tab to Des tab function moveSafeRows() { v ...

Maintaining data after page reload in Angular

angular.module('eventTracker', []) .controller('MainCtrl', ['$scope', 'Event', function($scope, Event){ $scope.eventData = {} $scope.onSubmit = function(){ Event.Add($scope.eventData) $scope. ...

What is the process for playing an audio file on a mobile device?

Recently, I encountered an issue with a jQuery statement that plays a created audio file. Strangely, the file plays correctly on my computer but not on my mobile phone. Despite max volume settings, there is no sound when trying to play it on the mobile dev ...

Arrange DIV elements sequentially with HTML, JQuery, and CSS

Live Demo: Live Demo HTML: <div class="target"> <img src="bg-clock.png" alt="jQuery" /> </div> <div class="target2"> <img src="bg-clock.png" alt="jQuery" /> </div> CSS: .target, .target2 { ...

The information in JSON format has been received but it is empty

Hey there! I have a JSON request that looks like this: $.ajax({ url: "/DeviceUsage/FreeDevice", type: "POST", data: JSON.stringify({ data: Ids }), error: function (data) { alert("error " + data); }, ...

retrieving the 'sibling' element from an array

I've been grappling with a challenge related to handling the following: Suppose I have a JSON object retrieved from a REST endpoint like this; SomeArray = [{"id":"1","genre":"Folk"}, {"id":"2","genre":"punk"}, {"id":"13","genre":"Punk (original)"}, ...

Upon attempting to open Google Maps for the second time, an error message pops up indicating that the Google Maps JavaScript API has been included multiple times on this page

Currently, I am utilizing the npm package known as google-maps and integrating it with an angular material modal to display a map. However, upon opening the map for the second time, an error message is triggered: You have included the Google Maps JavaScri ...

What is the best method for transferring images to a node.js server using Axios?

Is there a method to utilize axios for sending an array of images or a single image to node? My current axios code (implemented in react js on the frontend): onFormSubmit(event){ event.preventDefault(); let payload = this.state; console.log(" ...

Viewing e-commerce thumbnail galleries is made easy with this unique

Typically seen on online shopping sites, I feature a main image along with around 5 smaller thumbnails. My goal is to have the main image switch when one of the smaller thumbnails is clicked, offering different perspectives of the product. For reference, y ...

Warning message for repetitive keys in template loop

<template v-for="errors in validationErrors"> <li v-for="(error, errIdx) in errors" :key="errIdx">{{ error }}</li> </template> An issue arises with the above code: The system detects duplicate keys: '0'. This might ...