Guide on creating a rectangle in HTML without using the canvas element

The concept is clearer in this image

In the photo provided, I utilized canvas for drawing; however, I am interested in exploring a different approach that would allow me to create draggable rectangles with unique IDs. For instance, if I were to use div instead of canvas, manual drawing of rectangles like in the photo would not be possible. There may be a solution that I'm unaware of. Upon researching this topic, I found that most people utilize tools like paper.js, but I find them limited to resizing or drag and drop actions which is why I chose not to use them.

function lettersOnly(input) {
  var regex = /[^a-z]/gi;
  input.value = input.value.replace(regex, "");
}

jQuery(document).ready(function($) {

  //Canvas
  var canvas = document.getElementById('canvas');
  var ctx = canvas.getContext('2d');

  //Variables
  var canvasOffset = $("#canvas").offset();
  var canvasx = canvasOffset.left;
  var canvasy = canvasOffset.top;
  var last_mousex = 0;
  var last_mousey = 0;
  var mousex = 0;
  var mousey = 0;
  var mousedown = false;
  var shapes = [];
  var width;
  var height;
  // make var col a global variable
  var col = "black";
  var ad = "";

  //Mousedown
  $(canvas).on('mousedown', function(e) {
    last_mousex = parseInt(e.clientX - canvasx);
    last_mousey = parseInt(e.clientY - canvasy);
    mousedown = true;
  });

  //Mouseup
  $(canvas).on('mouseup', function(e) {
    const lastPos = {
      lastMouseX: last_mousex,
      lastMouseY: last_mousey,
      rectWidth: width,
      rectHeight: height,
      color: col,
      name: ad
    };
    shapes.push(lastPos);
    mousedown = false;
  });

  //Mousemove
  $(canvas).on('mousemove', function(e) {
    mousex = parseInt(e.clientX - canvasx);
    mousey = parseInt(e.clientY - canvasy);

    if (mousedown) {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      width = mousex - last_mousex;
      height = mousey - last_mousey;
      col = $("#color").val();
      ad = $("#name").val();
      if (shapes.length > 0) {
        for (var i in shapes) {
          ctx.beginPath();
          ctx.strokeStyle = shapes[i].color;
          ctx.rect(shapes[i].lastMouseX, shapes[i].lastMouseY, shapes[i].rectWidth, shapes[i].rectHeight);
          ctx.fillText(shapes[i].name, shapes[i].rectWidth - shapes[i].lastMouseX, shapes[i].rectHeight - shapes[i].lastMouseY);
          ctx.stroke();

        }
      }
      ctx.beginPath();
      ctx.rect(last_mousex, last_mousey, width, height);
      ctx.strokeStyle = col;
      ctx.lineWidth = 3;
      ctx.fillText(ad, 100, 100);
      ctx.stroke();

    }
    $('#output').html('Current Coordinate: ' + mousex + ', ' + mousey + '<br/>Last Coordinate: ' + last_mousex + ', ' + last_mousey);

  });
});
.topnav {
  background-color: #333;
  overflow: hidden;
}


/* Style the links inside the navigation bar */

.topnav a {
  float: left;
  color: #f2f2f2;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
  font-size: 14px;
}


/* Change the color of links on hover */

.topnav a:hover {
  background-color: #ddd;
  color: black;
}


/* Add a color to the active/current link */

.topnav a.active {
  background-color: #4CAF50;
  color: white;
}

#color {
  border: 1px solid black;
  font-family: 'Times New Roman', Times, serif;
  font-size: 14px;
  margin: auto;
  padding: 0;
  position: absolute;
  top: 0;
  left: 45%;
  right: 0;
  text-align: center;
}

...
...more content...

Answer №1

Is this the kind of thing you’re looking for? When you mention "draw", this is what comes to mind.

To achieve this effect, you’ll need to determine the mouse position in the mousedown event and the mousemove event. Then, calculate the difference between the initial mousedown coordinates (x, y) and the current mousemove coordinates to set the width and height of the div being drawn.

It’s also important to keep track of whether the mouse button is still pressed while moving it to avoid accidentally drawing a div without intention.

Once the mouse button is released (“mouseup”), you can enable your draggable/resizable functionality.

You can see an example on this JSFiddle link.

$(function() {
  var widget;
  var x;
  var y;
  var finX;
  var finY;
  var ismousedown = false;
  $(document).on({
    mousedown: function(event) {
      if ($(event.target).attr('class') == 'wrapper') {
        x = event.pageX;
        y = event.pageY;
        $('body').append('<div class="widget" style="top:' + y + 'px; left: ' + x + 'px;"></div>');
        widget = $('.widget').last();
        ismousedown = true;
      }
    },
    mousemove: function(event) {
      if (ismousedown == true) {
        finX = event.pageX;
        finY = event.pageY;
        widget.width(finX - x);
        widget.height(finY - y);
        widget.css({
          'width': (finX - x) + '!important',
          'height': (finY - y) + '!important',
          'display': 'block',
          'border': '2px dashed #ccc'
        });
      }
    },
    mouseup: function(event) {
      ismousedown = false;
      widget.css({
        'background': '#222',
        'border': '0',
        'cursor': 'move'
      });
      initDraggable();
    }

  });

  // in case you need to reinitialize later.
  function initDraggable() {
    $('.widget').draggable({});
  }
});
html,
body {
  height: 100% !important;
  position: relative;
}

.wrapper {
  position: relative;
  height: 100% !important;
  width: 100% !important;
}

.widget {
  display: block;
  position: absolute;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<div class="wrapper">

</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

A guide on sending a React component as a parameter to an HTML input element

Is it possible to pass a React component as an attribute to an HTML input? class Test extends React.Component { render() { return "test"; } } function App() { return ( <input type="text" value={<Test />} /> ) } The issue I ...

Error Alert: It is required that only variables are passed by reference in the file located at /home/indiamaz/public_html/musicwala.cf/get-zip.php on line 31

A few days ago, my PHP project was running smoothly without any errors. However, for the past two days, I have been encountering a Strict Standards error and a Warning message in my code. I'm unsure of what caused this sudden issue and would appreciat ...

The $POST method is failing to update the information

I've encountered an issue with my script that I can't seem to figure out. After numerous tests, it seems like the main problem lies within the Ajax request. Interestingly, I have used the Ajax request successfully in a previous version of my scri ...

Vue.js - the value of this is not defined

<div class="content-chart"> <chart :type="'line'" :data="lineData" :options="options"></chart> </div> In the template section above, a component is defined to render a chart using Chart.js. The script below handles the l ...

Automatically append version number to requests to avoid browser caching with Gulp

When deploying my project, I utilize gulp to build the source files directly on the server. In order to avoid caching issues, a common practice is to add a unique number to the request URL as explained in this article: Preventing browser caching on web app ...

Enabling the submit button only when text is entered in the text fields using jQuery

I have a script that automatically submits a form when two textfields are filled using variables from local storage. The script checks if the variables for email and password are not null before submitting. if (localEmail != null && localPwd != null) { ...

What is the best way to add a delay to ajax using setTimeout when working within a switch case

Is there a way to add a delay of 20 seconds to the Ajax function before displaying the next chat line? I'm trying to implement a feature where Ajax waits a few seconds before showing the next chat line that is submitted. For instance, imagine that t ...

"Creating dynamic radio buttons within a dynamic table using Ajax and jQuery: a step-by-step guide for toggling

Looking to generate a dynamic html table with data retrieved from a web method in asp.net using Ajax jQuery. One of the fields is a boolean value that needs to be associated with radio buttons. However, encountering an issue where setting attributes like ...

Inserting items into the document after updating the list with fresh data

I populate an array of objects when a button is clicked. The array only has 10 objects initially, but users can add more after it's loaded into the DOM. Here's how I handle this: $scope.Information = []; $.each(data, function (i, v) { if ...

Troubleshooting problems with jQuery Chosen plugin post-AJAX request

I'm encountering an issue with the plugin called jquery-chosen not applying to a control that is reconstructed by an ajax call. Despite exploring other suggestions, I have yet to find a solution that works. The versions of jquery and jquery-chosen be ...

Using $.get inside of a .click event handler

I'm a bit confused about what's happening with this particular piece of code. I have a button element that in theory should trigger the script below when clicked. When I try it in Chrome, everything seems fine - the button works, but the file isn ...

It seems that using the SVG <mask> tag is necessary for Firefox to display correctly, but it causes issues with CSS mask in

I need assistance with masking content using an external SVG image. Currently, I'm using the following code: #homepage-banner .desktop-slider.masked { -webkit-mask:url(news-panel-mask.svg) left top no-repeat; /* Chrome/Safari (Webkit) */ mask: ur ...

Tips for transferring PHP variable from a drop down menu

Hello, I am currently working on creating a dropdown menu using the <select> tag. My goal is to have it so that when someone clicks on one of the options in the dropdown, a new window opens. Additionally, I want the PHP variable from the main page to ...

Updating the iFrame source using jQuery depending on the selection from a dropdown menu

I want to create a dynamic photosphere display within a div, where the source is determined by a selection from a drop-down menu. The select menu will provide options for different rooms that the user can view, and the div will contain an iframe to showca ...

Tips for utilizing a Three.js curve to guide the movement of a mesh along a specified path

Developing an animation, currently at this stage: http://jsfiddle.net/CoderX99/66b3j9wa/1/ Please avoid delving into the code, it's written in CoffeeScript and may not be beneficial for your mental well-being. Imagine a "nordic" landscape with ship ...

Stylish mobile navigation styles with CSS

Hey there, I appreciate any help you can provide. I'm having trouble figuring out the right CSS code to modify the colors of my Mobile Menu only... I'd like to change the placeholder text as well as the text and background of the drop-down menu ...

How can I modify this code to be more responsive using float or relative positioning without introducing any errors?

I'm currently struggling to create a responsive web page that adjusts to any screen size automatically. Here is the code I have so far, including both HTML and CSS. What changes can I make to ensure the elements are properly placed regardless of the s ...

Using a Default Value in a Destructured Function Parameter Results in a ReferenceError

When working on setting a default value for the db in my CRUD functions for testing purposes, I encountered a peculiar issue that has left me puzzled. Here's the snippet of code that caused the trouble: import { db } from './firebase' func ...

Trouble locating SVG element in Google Calendar when using Python

I'm currently facing an issue while attempting to delete an event from my Google Calendar. An error keeps popping up indicating that the webdriver is unable to locate the element. Here's an image of the problematic element. Exception has occurred ...

When attempting to add a new row to a table, the function fails to function properly

I am facing an issue with my dynamic HTML table. Each row in the table should have two cells whose values are multiplied together. I have created a function to achieve this, but it only works on the first row of the table and not on any new rows added by c ...