Instructions for sketching a square at predetermined coordinates

Looking for a simple function to draw a box at specific coordinates x and y. I've searched for guides, but they all seem to provide excessive or insufficient information. Thanks in advance!

Answer №1

I created this script a while back, so there may be room for improvement, but the concept is to track the cursor position on mousedown and add an onmousemove listener. As you move the mouse, the script adjusts the size of a box based on the cursor position. When you release the mouse, the onmousemove listener is removed.

https://jsfiddle.net/47nmp90w/

dragBox = (function() {

  var _curX;
  var _curY;
  var _workingEl;
  var _docEl = document.documentElement;

  if (_docEl.scrollTop === 0) {
    var testDocEl = _docEl.scrollTop;
    _docEl.scrollTop++;
    _docEl = testDocEl+1 === _docEl.scrollTop-- ? _docEl : document.body;
  }

  return {

    drag: function(e) {
      var evt = e ? e : window.event;
      _width = Math.abs(_curX - evt.clientX);
      _height = Math.abs(_curY - evt.clientY);
      if (evt.shiftKey) {
        var minDimension = Math.min(_width, _height) + 'px';
        _workingEl.style.width = minDimension;
        _workingEl.style.height = minDimension;
      } else {
        _workingEl.style.width = _width + 'px';
        _workingEl.style.height = _height + 'px';
      }
      _workingEl.style.left = Math.min(_curX, evt.clientX) + _docEl.scrollLeft + 'px';
      _workingEl.style.top = Math.min(_curY, evt.clientY) + _docEl.scrollTop + 'px';
    },

    draw: function(e) {
      var evt = e ? e : window.event;
      if (evt.which === 1) {
        _curX = evt.clientX;
        _curY = evt.clientY;
        _workingEl = document.createElement('div');
        _workingEl.className = 'drawing';
        document.body.appendChild(_workingEl);
        window.onmousemove = dragBox.drag;
        window.onmouseup = function() {
          window.onmousemove = null;
          _workingEl.className = 'done';
          _workingEl = false;
        }
      }
    }

  };

})();
window.onmousedown = dragBox.draw;

Edit

If you want to create a box with specific dimensions, you can do so by setting the height and width styles, along with left and top positions based on the x and y coordinates.

https://jsfiddle.net/RDay/47nmp90w/4/

var createButton = document.getElementById('create');
var xPosInput = document.getElementById('x-pos');
var yPosInput = document.getElementById('y-pos');
var widthInput = document.getElementById('width');
var heightInput = document.getElementById('height');
var target = document.getElementById('target');

createButton.onclick = function() {
  var xPos = xPosInput.value;
  var yPos = yPosInput.value;
  var width = widthInput.value;
  var height = heightInput.value;

  var box = document.createElement('div');
  box.className = 'box';
  box.style.left = xPos + 'px';
  box.style.top = yPos + 'px';
  box.style.width = width + 'px';
  box.style.height = height + 'px';
  box.style.left = xPos + 'px';

  target.appendChild(box);

};

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

Restore the initial content of the div element

Currently, I am utilizing the .hide() and .show() functions to toggle the visibility of my page contents. Additionally, I am using the .HTML() function to change the elements inside a specific div. $('#wrap').html(' <span id="t-image"> ...

What is the advantage of using event.target over directly referencing the element in eventListeners?

Suppose there are several buttons in an HTML file and the following code is executed: const buttons = document.querySelectorAll('button'); buttons.forEach((btn) => { btn.addEventListener('click', (e) => { console.log(btn.te ...

Retrieving the IDs of all socket connections in a Node.js Socket.IO array

I currently have a complex program utilizing socketio 0.9 where I am storing all the sockets id in arrays like so: var clients = {}; To uniquely identify and store my sockets, I assign them a serial and then set the 'socket' key with its actual ...

Converting RSS title to HTML format with the help of JavaScript

I am currently working on populating a menu on a webpage with the 5 latest topics from our site's RSS newsfeed using JavaScript (specifically jQuery version 1.9.1). I have been searching for a solution, but most answers I find reference deprecated scr ...

CSS declarations that have not been acknowledged or acknowledged

While working on a client's stylesheet today, I came across the following code: p { -webkit-hyphens: auto; -webkit-hyphenate-character: "\2010"; -webkit-hyphenate-limit-after: 1; -webkit-hyphenate-limit-before: 3; -moz-hyphens: manual; orphans: ...

Using CSS, eliminate the drop-down menu from the main navigation on Squarespace

While working on my Squarespace website, I've been impressed with how the FAQ page/questions are structured. However, a drawback is that it creates a clunky drop-down menu when hovering over the FAQ tab in the main navigation. You can see an example ...

Tips for avoiding anchor tag text from being split across two lines when resizing

One issue I am facing is with an anchor tag that displays the name of the logged-in person. The problem arises when resizing the browser window, causing the name to split across two lines. Is there a way to prevent this from happening? ...

Animate jQuery Images - Transform and smoothly reveal element

Hey there! I've managed to create a color switcher that gives a sneak peek of different themes. Currently, it simply switches the image source and loads the new image. But I'm curious if it's possible to add a fadeIn effect to enhance the t ...

What are the steps to personalize Twitter Bootstrap with Less for changing the height of the Navbar?

I recently stumbled upon some interesting articles that explain how to customize various elements of Twitter Bootstrap using LESS. You can check out one of the articles here and find more information about Twitter Bootstrap here. However, I am still unsure ...

Add owl carousel to your npm project in any way you see fit

After struggling for a while, I finally wanted to implement owl-carousel, but couldn't figure out how to connect it using npm and webpack. The official NPM website states: Add jQuery via the "webpack.ProvidePlugin" to your webpack configuration: ...

"Escape the confines of traditional div sections with the dynamic features of

In the beginning, I have arranged two rows of three divs on my webpage, which is how I intend to use them later. However, when testing the 'mobile view', the divs in the section overflow and move into the next part below the section. This causes ...

Troubleshooting the Ng2-Charts Linechart to display all values instead of just the first two

Starting a new Angular application with the Angular-CLI (beta 22.1) has presented an issue when adding test data (5 values) to a chart. The scaling appears incorrect, displaying only the first two values stretched across the entire length of the graph (ref ...

The Autocomplete field's label remains visible even after the form is submitted

I am currently developing a feature that allows users to select an option in the Autocomplete component. In the parent component, I pass these props: const filterDropdownConfig: FilterSelectAutocomplete = { data: scenariosList, label: { className: &apos ...

Retrieve the html code from a PHP backend by utilizing core-ajax within the Polymer framework to store the information

Is there a way to retrieve JSON data from a PHP script that contains HTML tags, and display the data properly in an HTML format without seeing the tags? Currently, HTML tags are displayed as: <h1>hello</h1> instead of rendering as: hello I am ...

Exploring the concept of promise.reject() and the art of passing an object as a parameter

By passing response.json in Promise.reject(), I intended for it to be accessible in the catch block. However, it appears as undefined in the catch block. const checkResponse = (response) => { if (response.status >= 200 && response.status & ...

Python.Selenium. Unable to locate current element. Techniques for switching frames

I am trying to collect feedback from a specific page at this URL. After waiting for the page to load, I attempted to locate elements using Google Chrome inspector. However, Selenium is unable to find these elements, and I also could not find them in the p ...

Troubleshooting a Next.js background image problem when hosting on Netlify

I've encountered an issue while attempting to deploy a nextjs website on Netlify. Everything works perfectly on my local server, but once it's on Netlify, the background image URL changes and the image becomes invisible. Original CSS code: backg ...

What could be causing my CSS code to not function properly within Vue.js?

Having trouble with css in VueJs. I can't seem to figure out what I'm doing wrong. Generally, my scoped style css works fine in vuejs, I can target ids and classes without any issues. The problem arises when trying to change the internal css va ...

Struggling with implementing React routing in version 4.0

Struggling to route multiple pages using BrowserRouter in Reactv4. Many online guides are outdated and not working with the latest version. Here is my setup: Index.js: import React from 'react'; import ReactDOM from 'react-dom'; impo ...

Chrome displaying an extJs Button image

Could it be that Chrome is evolving into the new IE in terms of CSS issues? Here is the code I have for creating ExtJS buttons within an accordion: var button = Ext.create('Ext.Button', { text: '<img src="'+resp.sellers.externa ...