Utilizing Bresenham's line drawing algorithm for showcasing box contours

I am seeking a similar behavior to what is demonstrated on , but with some modifications to the boxes:

div {
  display: inline-block;
  width: 100px;
  height: 100px;
  border: 1px solid black;
  cursor: pointer;
}

div.selected,
div:hover {
  background-color: red;
  color: white;
}
<div>A</div>
<div>B</div>
<div>C</div>

I would like the ability to click on one box, drag it, and have the color of the other boxes change as well.

I previously posted about this issue, but the accepted answer did not meet my needs. I am specifically looking for the same functionality as in the provided link above.

Thank you.

Answer â„–1

When implementing Bresenham’s Line Generation algorithm, keep the following assumptions in mind:
1) Lines are drawn from left to right.
2) The starting point (x1, y1) is less than the ending point (x2, y2).
3) The slope of the line falls between 0 and 1, meaning it is a diagonal line from lower left to upper right.

var x1, y1, x2, y2;
    function handleMouseDown(e){
          x1 = +e.target.dataset.x;
          y1 = +e.target.dataset.y;
          
          container.addEventListener('mousemove', handleMouseMove);      
          e.preventDefault();
    }
    function handleMouseMove(e){
          x2 = +e.target.dataset.x;
          y2 = +e.target.dataset.y;
          
          var ele = document.querySelectorAll('[data-x][data-y]');
          ele.forEach(function(val){
              val.classList.remove('selected')
          });

          bresenham(x1, y1, x2, y2);     
          
          
    }
    function handleMouseUp(e){
        var ele = document.querySelectorAll('[data-x][data-y]');
        ele.forEach(function(val){
            val.classList.remove('selected')
        });
        e.preventDefault();
        container.removeEventListener('mousemove', handleMouseMove);      
    }
    function bresenham(x1 , y1, x2 , y2){

         var m_new = 2 * (y2 - y1);
         var slope_error_new = m_new - (x2 - x1);
         for (var x = x1, y = y1; x <= x2; x++)
         {
             var ele = document.querySelector('[data-x="'+x+'"][data-y="'+y+'"]');
             ele.classList.add('selected');     
            
            slope_error_new += m_new;
       
            if (slope_error_new >= 0)
            {
               y++;
               slope_error_new -= 2 * (x2 - x1);
            }
         }
    }
    var container = document.getElementById('container');
    container.addEventListener('mousedown', handleMouseDown);
    container.addEventListener('mouseup', handleMouseUp);
div {
    display: inline-block;
    width: 100px;
    height: 100px;
    border: 1px solid black;
    cursor: pointer;
  }

  div.selected{
    background-color: red;
    color: white;
  }
<span id="container">
     <div data-x="0" data-y="0" >A</div>
     <div data-x="1" data-y="0" >B</div>
     <div data-x="2" data-y="0" >C</div>
</span>

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

Is there a way for me to import a variable from one file and use require() to access it in another file?

This is my current folder structure: collegesapp -- |-- node_modules -- express | -- connect | -- jade | -- passport |-- routes -- routes.js ...

Avoid running multiple YouTube views simultaneously within an AngularJS application

Currently, I have an Angularjs application that displays a list of Youtube videos utilizing the videogular node module. An issue has arisen where users can play multiple Youtube videos simultaneously, leading to potential violations of Youtube's poli ...

What is the best way to retrieve the response from a POST request in Angular JS?

I am currently utilizing node, express, mongoose for the backend and angular js for the front-end. I have a form through which I am sending a post request. <div class="alert alert-success" ng-show="success"> {{success}} </div> <div class ...

Customizing an image with personalized text and then sending it to a server using a combination of javascript and

Looking for a way to add text to an image saved on the server, then save the edited image back to the server. I've heard using canvas is the best approach, but struggling to find the specific solution I need. ...

What could be the reason for JavaScript code successfully exporting to Excel using the old office extension .xls but encountering issues when trying to export

I am currently working on exporting an HTML table to Excel using JavaScript. I have encountered an issue where it does not export to the newer version of Excel with the xlsx extension. However, it works fine and exports to older versions of Excel with the ...

Is it possible to transform div containers into unique shapes?

I'm working on a design where I want to have two divs that resemble teeth, one on the top half of the page and the other on the bottom half. The concept is to make these mouth piece divs open and close as you scroll with the mouse, revealing the conte ...

Create a duplicate of a div element, including all of its nested elements and associated events, using

Attempting to duplicate a div containing input fields but the event listeners are not functioning. Despite performing a deep copy in the following manner - let rows = document.querySelectorAll('.row'); let dupNode = rows[0].cloneNode(true); sh ...

Move on to a different screen in a React Component once the data has been fetched

Currently, I am delving into the world of React and TypeScript and attempting to utilize "react-router-dom" in order to create a login component that will interact with my backend server. Essentially, my goal is to develop a "Login" class that, upon form ...

Unexpected token error occurs when making cross-domain AJAX requests to the server and receiving a JSON object

I have set up an express server to handle get requests to specific url endpoints. When responding to these requests, I am sending back data in JSON format to enable making Ajax calls and retrieving data from the page. To allow for cross-domain requests, I ...

Uploading several files with Laravel and Vue JS in one go

Recently, I have been working on a project where I need to upload multiple image files using Vue JS in conjunction with Laravel on the server side. This is the snippet from my Vue template: <input type="file" id = "file" ref="f ...

Include a class above the specified element; for instance, apply the class "act" to the "<ul>" element preceding the "li.item1"

Hello there! I need some assistance, kinda like the example here Add class and insert before div. However, what I really want to do is add the class "act" to a class above that matches the one below: Here's how it currently looks: <ul> ...

particular shade for button border and background

I'm looking to create a button using Material UI that has a specific design. Right now, I've only been able to achieve this: https://i.stack.imgur.com/xvv7s.png Here is the code I am currently using. If anyone can help me identify what I'm ...

Triggering a form submission in JavaScript when a selection is changed

Welcome to my WordPress site! If you would like to check it out, visit this link. Currently, I have a form located next to the text "Filter By Location:". My goal is to have the form submitted automatically when one of the options is selected (onChange). ...

Enhance your PrimeVue experience with the power of Tailwind CSS

After installing PrimeVue, I encountered an issue where the component style was not working, but Tailwind CSS was functioning correctly. It seems that when I install Tailwind first, it works fine until I add Primevue's button component, which then cau ...

"Looking to spice up your website with a dynamic background-image

I've encountered a problem with my CSS code for the header's background image. Despite trying various methods to create a slideshow, nothing seems to be working. Can someone provide guidance? I have four banner images named banner1, banner2, bann ...

html2canvas bottom margin

I coded this in react function download(element) { html2canvas(element).then((canvas) => { window.open(canvas.toDataURL('image/png')); }); } return ( <div className='box' onClick={( ...

Steps for Renewing Firebase Session Cookie

I am currently developing a web application utilizing Node.js/Express.js for the backend, with Firebase being used for user authentication. To manage user registration and other tasks, I rely on the Firebase Admin SDK. When a user attempts to log in, the ...

Creating a series of promises in a structured chain

How can the code structure be improved, especially regarding exception handling within a "promise chain"? $("#save").click(function(e) { e.preventDefault(); let $self = $(this); let profile = {} $self.prop("disabled" ...

When scrolling the page, the Circle Mouse Follow feature will dynamically move with your cursor

Hey everyone! I'm currently working on implementing a mouse follow effect, but I'm facing an issue where the circle I've created moves along with the page when scrolling, instead of staying fixed to the mouse. Any suggestions or tips would b ...

Hovering over an SVG icon will trigger an animation

I am trying to achieve an animated effect on an SVG line icon only when it is hovered over. I want the icon to remain static when not being hovered. While I have managed to animate the drawing effect and make it work somewhat on hover, I am facing an issue ...