Creating a line that connects Point A to Point B using HTML, CSS, and JavaScript

Essentially, I am looking to create a line that connects point A (0vh|0vw) to point B (50vh|50vw).
Initially, I considered using a div with a border and a 1px height that is rotated to achieve the desired effect.

However, the issue arises when the size of the site changes due to an uncommon monitor or window resizing, causing the rotation angle to be incorrect.

Therefore, my goal is to draw a line from a set point A to point B while automatically adjusting the rotation degree as the site is resized.

Answer №1

Using an SVG, as suggested by manassehkatz, can be a great solution.

<svg width="100%" height="100%" style="position:absolute;top:0;left:0;">
  <line x1="0" y1="0" x2="50vw" y2="50vh" style="stroke:red;stroke-width:2" />
</svg>

An alternative option is to utilize a canvas, but this method will require custom resizing and rendering.

const ctx = document.getElementById('line-drawing').getContext('2d');

function update() {
  Object.assign(ctx.canvas, {
    width: window.innerWidth,
    height: window.innerHeight,
  });
}

function render() {
  const { width, height } = ctx.canvas;
  ctx.clearRect(0, 0, width, height);
  ctx.beginPath();
  ctx.moveTo(0, 0);
  ctx.lineTo(~~(width / 2), ~~(height / 2));
  ctx.lineWidth = 2;
  ctx.strokeStyle = 'red';
  ctx.stroke();
}

update();
render();

window.addEventListener('resize', () => {
  update();
  render();
});
#line-drawing {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}
<canvas id="line-drawing"></canvas>

Answer №2

An easy method to achieve this effect using CSS is by creating a clipped div that covers the entire viewport.

Take a look at the following code snippet for reference:

<style>
  .stripe {
    width: 100vw;
    height: 100vh;
    background: blue;
    position: fixed;
    clip-path: polygon(0% 0%, 20% 0%, 50% 50%, 80% 100%, 100% 100%, 100% 0%);
  }
</style>
<div class="stripe"></div>

Answer №3

In my opinion, opting for an hr instead of a div (as it essentially functions as a rotated horizontal rule) would be a better choice. Nevertheless, achieving this using CSS is definitely possible. It does require some functionalities that, currently, only function in Safari and Firefox: the CSS sqrt() and atan2 functions.

We can define the width of our hr to match the hypotenuse of your triangle, and apply rotation using atan2 (for further insights on this unique function, refer to its wikipedia article. Its significance reaches to the extent of being directly integrated into CPUs as a fundamental machine instruction) to determine an angle based on distance and rise:

main {
  --w: 200;
  --h: 100;
  width: calc(1px * var(--w));
  height: calc(1px * var(--h));
  background: red;
}

.line {
  padding: 0;
  margin: 0;
  height: 0px;
  border: 0.5px solid black;
  transform-origin: 0 0;

  /* line from (0,0) to (50% width, 50% height): */
  --lw: calc(var(--w) / 2);
  --lh: calc(var(--h) / 2);

  /* calculate our hypotenuse length and angle: */
  --m: calc(pow(var(--lw), 2) + pow(var(--lh), 2));
  --hyp: sqrt(var(--m));
  width: calc(1px * var(--hyp));

  --angle: atan2(var(--lh), var(--lw));
  transform: rotate(var(--angle));
}
<main>
  <hr class="line"/>
</main>

Naturally, resorting to SVG would offer a much simpler solution with improved compatibility =D

Answer №4

Experiment with setting the body to 100vh and 100vw, then use only px units inside for better adaptability of the screen size without affecting the stick's dimensions.

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

Determine the index of a specific character within a string using a "for of" loop

How can I obtain the position of a character in a string when it has been separated programmatically using a for...of loop? For instance, if I wish to display the position of each character in a string with the following loop: for (let c of myString) { ...

AngularJS: Creating a unique directive for verifying the availability of a username - no duplicates allowed

I have a registration form that includes a username textbox. I would like to implement a custom directive that will check if the entered username already exists in the database. Here is the api implementation: /*get the unique username*/ $app->get(&ap ...

What could be causing the Gruntfile to throw an error?

Getting an unexpected error while trying to run grunt $ grunt Loading "Gruntfile.js" tasks...ERROR >> SyntaxError: Unexpected token : Warning: Task "default" not found. Use --force to continue. Execution terminated due to warnings. Here is my ...

What is the most effective method for serializing SVG data from the client's Document Object Model (DOM

As I delve into the world of creating interactive SVG/AJAX interfaces, I find myself faced with a challenge. Users are constantly manipulating elements on-the-fly and I want to give them the option to export their current view as a PNG image or an SVG docu ...

Separation between inline elements with a line break

I am faced with the challenge of placing the a tag on a new line while maintaining center alignment, without being able to modify the HTML. The display:block option extends the clickable area beyond the text. See the screenshot below for the desired outco ...

Creating an object with an array of objects as a field in MongoDB: A step-by-step guide

I have a unique schema here: const UniqueExerciseSchema = new Schema({ exerciseTitle: { type: String }, logSet: [{ weight: { type: Number }, sets: { type: Number }, reps: { type: Number }, }], }); After obtaining the da ...

Choose links in the div and apply "motion effects."

Can anyone help me figure out why the color change for links in a div on mouseover/mouseout isn't working? Here is the HTML code: <div id="Navigation"> <a href="#">Products</a> <a href="#">Pro ...

Eliminating the gray background using CSS

How can I remove the gray background that automatically appears in my CSS header? .header { padding: 60px; margin: 20px auto auto auto; width: 1400px; border-radius: 10px; text-align: center; background: # ...

When an element possesses a particular class, modify the css styling of a different

My menu is an unordered list, with each menu item gaining the "active" class when clicked. This works perfectly fine. However, I have an arrow positioned absolutely and its "top" style needs to change based on which list item has the "active" class. Curr ...

What is the best way to prevent elements in the split function from being stored in an array?

Currently, I am attempting to utilize the split() method in Javascript to split elements into an array, a result that I do not desire. My goal is for the elements to be stored as values within an object. var string = "as1234,as5678,as6789"; var result = ...

Different methods for incorporating script-specific data into markup

How can we include extra meta data in HTML code to support client-side javascript functionality? Let's consider some straightforward examples: A list of contacts that, when clicked, displays their location on a map. For instance, how can we link la ...

Utilizing Ionic Storage to set default request headers through an HTTP interceptor in an Angular 5 and Ionic 3 application

I'm attempting to assign a token value to all request headers using the new angular 5 HTTP client. Take a look at my code snippet: import {Injectable} from '@angular/core'; import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from ...

Having trouble incorporating custom CSS into my Rails/Bootstrap project

I’m having trouble figuring out what I’m doing wrong. I’ve added custom files and tried to override the existing ones. application.css.scss @import 'bootstrap-sprockets'; @import 'bootstrap'; /* * This manifest file will be co ...

Notification Click Event for PWA Service Worker

I am attempting to display a notification and trigger an action when it is clicked. try { navigator.serviceWorker.getRegistration() .then(reg => { reg.showNotification("Check out the video clip!", { body: "Cl ...

Scaling down a retina image sprite using CSS: A step-by-step guide

Struggling with loading retina images? You're not alone. Many web developers face the challenge of scaling down high-resolution images effectively. Take, for example, two image sprites: one normal and one retina. The issue arises when you need to adju ...

Having trouble troubleshooting the jQuery button

When I click this button, it triggers an ajax call that updates the score_up value. I can't seem to figure out what's wrong. I attempted using Firebug, but it doesn't detect the JavaScript. Any help would be appreciated! Here is the jQuery ...

Creating a method in Angular that combines async/await functionality with Observables

After transitioning from using async/await to Observables in Angular, I am trying to refactor the following code snippet to make it work with Observables: async refreshToken() { const headers = this.authStorage.getRequestHeader(); const body = { ...

What is the best way to show an HTML file in a WebBrowser using C++?

Currently, I'm facing the challenge of displaying an HTML file in a WebBrowser within a Windows application. The issue lies in the fact that I am dealing with a local file instead of a URL. My attempted solution with file://MyWeb.html proved unsuccess ...

Mysterious JQuery attribute

I've come across a piece of code that utilizes an unfamiliar selector that I can't seem to figure out: $("div[tag=" + someVariable + "]").css("display", "block"); From what I gather, the selector is searching for a div element with an attribute ...

Why is TypeScript unable to recognize package exports? (using CommonJS as the module system and Node as the module resolution)

I have an NPM package that is built for ESM and CJS formats. The package has a dist folder in the root directory, which contains: dist/esm - modules with ESM dist/cjs - modules with CJS dist/types - typings for all modules In the package.json file, there ...