JSFiddle - React, Tailwind, and code Playground

by ronilan

HTML

// rectangular intersection of two given rectangles
<div id="my_rectangle"></div>
<div id="your_rectangle"></div>

JavaScript

// rectangular intersection of two given rectangles

function intersect(rect1, rect2){

	var result = {};
    
    if(rect1.x <= rect2.x){
    	
        if(rect1.x + rect1.width <= rect2.x + rect2.width){
         	result.x = rect2.x;
            result.width = rect1.x + rect1.width - rect2.x;
        } 
        
    } else {
        
         if(rect2.x + rect2.width <= rect1.x + rect1.width){
         	result.x = rect1.x;  
            result.width = rect2.x + rect2.width - rect1.x;             
        } 
        
    } 
    
    if(rect1.y <= rect2.y){
    	
        if(rect1.y + rect1.height <= rect2.y + rect2.height){

         	result.y = rect2.y;
            result.height = rect1.y + rect1.height - rect2.y;
        } 
        
    } else {

         if(rect2.y + rect2.height <= rect1.y + rect1.height){

         	result.y = rect1.y;   
            result.height = rect2.y + rect2.height - rect1.y; 
             
        } 
    }     
    
    return result;
    
} 

var my_rectangle = {

    //coordinates of bottom-left corner:
    'x': 3,
    'y': 5,

    // width and height
    'width': 10,
    'height': 4

}
  
 var your_rectangle = {

    // coordinates of bottom-left corner:
    'x': 2,
    'y': 6,

    // width and height
    'width': 10,
    'height': 4

}
 
 console.log(intersect(my_rectangle,  your_rectangle));