Use JavaScript to identify and color the intersecting area of two triangles that overlap on a webpage

I created two triangular divs using HTML and I am utilizing jQuery UI to enable them to be draggable.

Now, my goal is to overlap these two triangles and change the color of the overlapping area to a different shade. Here is an example:

https://i.sstatic.net/wc2yM.png

Can you provide any insights on how I can achieve this effect using jQuery?

$(document).ready(function() {

  $(".triangle").draggable();
})
#triangle_1 {
  width: 0;
  height: 0;
  border-left: 50px solid transparent;
  border-right: 50px solid transparent;
  border-bottom: 100px solid #00ff00;
}
#triangle_2 {
  width: 0;
  height: 0;
  border-left: 50px solid transparent;
  border-right: 50px solid transparent;
  border-bottom: 100px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class = "triangle"
id = "triangle_1" > </div>
    <div class="triangle" id="triangle_2"></div >

Here is my current solution using rectangles instead of triangles (link).

Answer №1

Discovering the point of intersection between two triangularly-styled DIVs is not supported by the jQuery API.

To uncover the "red intersecting triangle," you must turn to mathematics:

Step I: Identifying the vertex points of the red polygon

  1. Determine the 3 vertex points of both triangular divs.
  2. Use the #1 points from each triangle to identify the 3 line segments composing the sides of the triangles.
  3. Locate any intersection points between each line segment of triangle-A and triangle-B. Refer to the function below for guidance on finding these intersections.

If you locate precisely 3 intersection points in #3 above, it indicates that the original triangles intersect, forming a new triangle -- proceed to Step II...

Step II: Constructing a triangle polygon from the 3 intersection points found in Step I

  1. Determine the central point of your new triangle. This can be calculated as the average of its x and y coordinates:

    centerX = (vertex1.x + vertex2.x + vertex3.x)/3
    and
    centerY = (vertex1.y + vertex2.y + vertex3.y)/3

  2. Compute all angles from the centerpoint to each user's point utilizing

    Math.atan2( (vertex1.y-centerY), (vertex1.x-centerX) )
    ... doing likewise for vertex2 & vertex3.

  3. Arrange the points in ascending order based on the angles calculated in #2.

This trio of points forms the vertices of your red triangle.

Step III: Designing a new red div shaped like a triangle employing the vertices from Step II


Tools

Here is a Javascript function that determines the intersection of 2 line segments (if applicable):

// Obtain intersection point of 2 line segments (if any)
// Credit: http://paulbourke.net/geometry/pointlineplane/
function line2lineIntersection(p0,p1,p2,p3) {

    var unknownA = (p3.x-p2.x) * (p0.y-p2.y) - (p3.y-p2.y) * (p0.x-p2.x);
    var unknownB = (p1.x-p0.x) * (p0.y-p2.y) - (p1.y-p0.y) * (p0.x-p2.x);
    var denominator  = (p3.y-p2.y) * (p1.x-p0.x) - (p3.x-p2.x) * (p1.y-p0.y);        

    // Examine if Coincident
    // If the numerator and denominator for ua and ub are 0
    //    then the lines coincide.    
    if(unknownA==0 && unknownB==0 && denominator==0){return(null);}

    // Check for Parallel Lines 
    // If the denominator for ua and ub equations is 0
    //     then the lines are parallel. 
    if (denominator == 0) return null;

    // To ascertain the intersection of line segments 
    // evaluate whether ua and ub fall between 0 and 1.
    // Whichever lies within that range implies the corresponding
    // line segment contains the intersection point. 
    // If both lie within the range of 0 to 1
    // the intersection point resides within both line segments. 
    unknownA /= denominator;
    unknownB /= denominator;

    var isIntersecting=(unknownA>=0 && unknownA<=1 && unknownB>=0 && unknownB<=1)

    if(!isIntersecting){return(null);}

    return({
        x: p0.x + unknownA * (p1.x-p0.x),
        y: p0.y + unknownA * (p1.y-p0.y)
    });
}

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

Reordering Divs in Bootstrap 3 Specifically for Small Screens

Just getting started with my first responsive design project, and I'm wondering if it's possible to achieve something like this using Bootstrap 3. The goal is to switch from the current layout: https://i.stack.imgur.com/lABXp.jpg To https://i. ...

What is the scope parameter for the facebook-node-sdk in node.js?

https://github.com/amachang/facebook-node-sdk I decided to utilize this module in order to create a Facebook-integrated login for my node.js project, following the example provided with express: var express = require('express'); var Facebook = ...

Utilizing Java to extract dynamically generated content from an HTML page

I have an HTML page that looks like this: <html> <head> <!-- necessary java scripts --> </head> <body> <div id="content"></div> </body> After the page renders, a lot of dynamic html content is placed within ...

Activate a click event on an element using Simple HTML DOM

I need assistance in triggering a click on the element below and then retrieving its innertext. <a class="btn btn-sm btn-default" href="javascript:;" onClick="score(238953,this)">Show result</a> Once the "onClick" event is triggered, the elem ...

The width property is not being passed down to the table

I'm experiencing difficulties with the scaling of my body content. When the page is initially opened, it scales to 100%. However, when I resize the screen to make it wider, the content gets bigger but when I try to make it smaller again, it remains a ...

Netbeans lacks compatibility with JavaScript

Recently, I've been encountering code errors in my .js files while attempting to edit JavaScript using Netbeans 6.9. Even after upgrading to Netbeans 7.01 and enabling the JAVA plugin, the issue persists. I'm unable to create a new JavaScript tem ...

Managing Events in PHP

As a .net developer working on a php site for a friend, I've been making good progress. However, I have a question - is there something similar to a textchanged event in php? Here's what I'm trying to achieve: I want to dynamically populate ...

Two distinct iterations of the identical jquery version sourced from external sources

NOTE: This situation involves having two copies of jQuery with the same version number but different libraries loaded by external sources. This is distinct from the issue of using multiple versions of jQuery on a single page, as discussed here: Can I use m ...

The most efficient method for exchanging an array between PHP and Javascript

I have a set of data retrieved from a database stored in an array. The structure of the array is as follows; $rows[0]['id']=1; $rows[0]['title']='Abc'; $rows[0]['time_left']=200; $rows[1]['id']=2; $rows[ ...

implementing a sidebar menu using AngularJS

I am currently working with bootstrap and AngularJS to create a sidebar menu. Here is the code I have for it: <ul class="nav navbar-nav"> <li><a href="#"><span class="glyphicon glyphicon-send"></span> Link</a& ...

Navigating in React: How to Implement the Same Route for Different Scenarios Without Compromising Your Application

I'm facing a frustrating issue while trying to incorporate Redux state management and React Router. Despite searching extensively online, I can't seem to find a solution. My Redux state, named user, stores the details of a logged-in user. Upon l ...

The AngularJS function invoked itself within the structure

When working with my form, I encountered a problem involving custom input directives and text fields. In addition to these elements, there are buttons: one for adding a new input to the form which is linked to the function $scope.AddNewItem() in the contro ...

Unresponsive Ajax Calls in Laravel 5

I've been attempting to retrieve an Ajax response with Laravel 5, however, I'm encountering an issue. Here's the error that appears in the Chrome debugger: POST http://localhost:8000/getmsg 500 (Internal Server Error)send @ jquery.min.js:4a ...

Learn how to trigger a re-render in React to update a value stored in local storage

I need assistance in displaying a spinner with a percentage value during file uploads within my React application. To achieve this, I am utilizing Material UI's circular progress. My approach involves making a REST call using Axios to obtain the perce ...

Capture information from an HTML5 form and securely store it in a MySQL database

I have a simple web form that includes a "date" type input field. I want to retrieve the date entered by the user and store it in my MySQL database, which has a DATE type column. I am looking for some PHP/JS magic to facilitate the communication between t ...

How can you delay the return of a function until after another asynchronous call has finished executing?

Currently, I am working on implementing route authentication in my project. To achieve this, I have decided to store the authenticated status in a context so that other React components can check whether a user is logged in or not. Below is the relevant co ...

Is the Messenger Bot ignoring random users?

I am facing an issue that I need help explaining. The bot works perfectly when I use it from my own Facebook account. However, when I ask others to use it, the bot does not respond to them, even though I have received a green tick on the pages_messaging a ...

Challenges with cascading style sheets and the integration of PHP's include function

I am currently working on a PHP website project. I have implemented the include function in my main page to include other files, but I am facing an issue with the CSS when loading the main page. The CSS in the included files seems to be all messed up, maki ...

Extract the value from JSON data

I am faced with the challenge of extracting the value of slug from each child in a JSON dataset. The issue lies in the fact that I cannot predict how many children will be generated whenever new data is received. The generation of nested children is dynam ...

After upgrading from Windows 7 to Windows 10, I noticed that the CSS, HTML, and Bootstrap elements seemed to have lost their impact

<!DOCTYPE html> <html> <head> <title>Registration</title> <link rel="stylesheet" type="text/css" href="styles.css"> <link rel="stylesheet" type="text/css" href="bootstrap.css"> <link href ...