Is it possible to generate an HTML element by utilizing an array of coordinates?

I have a set of 4 x/y coordinates that looks like this:

[{x: 10, y: 5}, {x:10, y:15}, {x:20, y:10}, {x:20, y:20}]

Is there a way to create an HTML element where each corner matches one of the coordinates in the array?

I am aware that this can be done using canvas, but I am struggling to figure out how to achieve it with HTML elements.

The array will always consist of 4 coordinate sets. The final shape may be rotated or skewed, but will always be a "valid" shape achievable through CSS transformations.

Answer №1

Assuming you have the coordinates in the form of

[topLeft, bottomLeft, topRight, BottomRight]
for the original rectangle, you can recreate it using the following method:

const obj1 = [{x: 10, y: 5}, {x:10, y:15}, {x:20, y:10}, {x:20, y:20}];
const obj2 = [{x: 40, y: 80}, {x: 10, y: 160}, {x: 120, y: 80}, {x: 90, y: 160}];
const obj3 = [{x: 200, y: 30}, {x: 150, y: 80}, {x: 250, y: 80}, {x: 200, y: 130}];

function render(obj) {
  const skewX = obj[1].x - obj[0].x;
  const skewY = obj[2].y - obj[0].y;
  let translateX = Math.min(...obj.map(t => t.x));
  let translateY = Math.min(...obj.map(t => t.y));
  if(skewX<0) translateX -= skewX;
  if(skewY<0) translateY -= skewY;
  const scaleX = Math.abs(obj[0].x - obj[2].x);
  const scaleY = Math.abs(obj[0].y - obj[1].y);
  const el = document.createElement('div');
  el.style.width = '1px';
  el.style.height = '1px';
  el.style.backgroundColor = 'blue';
  el.style.transformOrigin = 'top left';
  el.style.transform = `matrix(${scaleX}, ${skewY}, ${skewX}, ${scaleY}, ${translateX}, ${translateY})`;
  document.body.appendChild(el);
}

render(obj1);
render(obj2);
render(obj3);

However, I suggest storing the shapes as their transformation matrix rather than vertices (if feasible).

Answer №2

If you're looking to create shapes without using canvas, one option is to draw SVG shapes by adjusting the coordinates within your object.

For deforming a div, a possible solution could be utilizing CSS transform:matrix, although it might require some experimentation to translate x/y coordinates to scale/skew/translate parameters for each corner.

If you're not deforming the div and just aiming to create a standard rectangular shape, you can convert your x/y coordinates into top; left; width; height; CSS properties.

Answer №3

Actually, HTML follows a tree-like structured DOM format. While it is possible to create a DOM using position: absolute (positioned absolutely with respect to the html element) and use top: y; left: x, in my opinion, there are no distinct advantages to doing it this way.

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

Check the status of the audio source URL using JavaScript

I am currently live streaming audio to my player using the Soundcloud API. <audio></aidio> <source src="soundcloud-track-url"></source> Within my code, I have added an onerror eventListener for both the <audio> and <sourc ...

What is the best way to run tests on this asynchronous function using Jasmine?

My role in the service is listo: function () { var promiseResolved = $q.defer(); setTimeout(function () { promiseResolved.resolve(true); }, 2000); return promiseResolved.promise; } During my testing ...

What is the best method for purging a previously stored variable from the cache when making an Ajax call and simultaneously passing a

I am encountering an issue with variable loading during the ajax call. Upon clicking, I pass a variable to the ajax call which then sends the value to a PHP script. The data obtained is from: rnc.csv DLRNC01 DLRNC02 DLRNC03 DLRNC04 DLRNC05 DLRNC06 DLR ...

Increasing a variable in MongoDB using Meteor.js based on the value of a variable in a separate document

I am facing an issue similar to this: I am struggling to modify multiple documents simultaneously. click: function() { var power = Meteor.user().power; var mult = Meteor.user().mult; Meteor.users.update({ _id: this.use ...

What is the most effective method for configuring an npm module?

I need help with configuring an npm module that I'm developing. The module includes two functions called notify.sms.send() and notify.email.send(), as well as an abstract function notify.send() that can call either or both of these functions. To hand ...

Utilizing JavaScript to assign class names to dynamically created elements from objects

I specialize in javascript and am working on adding the CSS class .is-slideUp to each card__item element created from a data object, in order to achieve a sliding-up animation effect. Although the .is-slideUp class name appears in the console, it does not ...

The number field is persisting with its content even after submitting, while the other fields successfully clear up

I am facing an issue where all fields clear up after submission except for the number field. I would appreciate any help on why this is happening and how to fix it. Thank you. Textfield number: const [number, setNumber] = useState(""); const han ...

Dynamic binding of CSS properties in AngularJS is a powerful feature that enables

I am attempting to dynamically bind the css property counter-reset in AngularJS. To see my efforts, check out this Fiddle link. Essentially, I aim to have the numbering of li elements begin with the number specified in the controller. Despite trying to us ...

Retrieve JavaScript functions as JSON or text in AngularJS and execute them

Currently, I am working on developing an AngularJS application and have come across a particular challenge that needs to be addressed: After making a web service call, I receive JavaScript code that looks like this: { "script":"function foo(a, b) { c = ...

Guide on aligning text along a baseline

CLICK HERE TO ENTER THE INTERACTIVE PLAYGROUND HTML: <div class="first">Text A</div> <div class="second">Text B</div> CSS: div { background-color: rgba(255, 0, 0, 0.3); /* For visualization only */ margin-top: 50px; ...

AngularJS encounters failure during shared data service initialization

As a newcomer to AngularJS, I aim to develop an application in adherence to John Papa's AngularJS style guide. To familiarize myself with these best practices, I have opted for the HotTowel skeleton. My application requires consuming an HTTP API endp ...

Additional unnecessary event listeners (deleteComponent) were provided to the component but could not be inherited automatically

Dear community, I am facing an issue with emitting events from my child component to the parent. Strangely, all other components work perfectly fine with the same code except for this particular one. Let me provide you with the relevant code snippets: Ch ...

"Showing Off Your Steam Inventory on Your Website: A Step-by-

My goal is to display a user's specific inventory on a webpage. I've tried using the following link: but it hasn't been helpful. ...

Node.js application abruptly halts without warning

I am currently working on a script to parse bitcoin blockchains using an asynchronous queue function from a popular library. However, I have encountered an issue where the code seems to stop without any error message during processing. What could be causin ...

Simulate mobile double tap screen resize using either jQuery or Javascript

UPDATE: I have encountered an issue that requires assistance. I am seeking help with implementing a functionality to automatically resize screen contents on mobile devices by calling a DoubleTap. The reason behind this requirement is that when a script up ...

CSS - image does not adhere to max-height when placed in a fluid container - link to jsFiddle

For instance: http://jsfiddle.net/vjqjv/7/ I am facing an issue with an image inside a container (refer to #slider-section in the jsFiddle) that has a fluid height and a set max-height. I have defined max-height and max-width for my image as 100% (check ...

"Navigate through the page by scrolling with your mouse all the way to 100

Is it possible to trigger an action when a user starts scrolling using the mousewheel? I've searched online but all I found was information on 100% scroll on click. I want the window to automatically be scrolled down to 100% as soon as the user starts ...

Can arrays be passed as function parameters in CrossRider without the need to convert them into objects first?

Our team is currently utilizing CrossRider to develop an extension specifically for Internet Explorer. We have a crucial object that is downloaded from , but we are facing an issue where arrays within this object are getting converted into objects with int ...

Tips for showcasing req.validationError in a form

I am currently working on validating a sign-up page using node.js/express. My main goal is to show the error messages generated by req.validationErrors() directly on my form. I have opted to use ejs instead of jade, and while I found a solution for display ...

The buttons within the bootstrap navbar are not properly collapsing or resizing when the screen size is decreased, causing them to overlap and maintain their

As a newcomer to bootstrap, I recently created a navbar with several buttons. However, when I reduce the screen size to 1000 pixels, the button text gets overwritten and the navbar extends off the screen. I don't want the navbar to collapse at this si ...