What is the best way to use canvas to precisely draw a line on the display at specific absolute coordinates?

As a newcomer to working with canvas and SVG, I am trying to create a line between two specific coordinates. For example, if I have two rectangles, I need to draw a line connecting their centers:

https://i.sstatic.net/Rc6qA.png

Here is what I have tried so far:

Using the following SVG code in HTML:

<svg version="1.1" id="line_2" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="100%" height="15px" xml:space="preserve">
  <path class="path2" fill="#01a09e" stroke-width="5" stroke="#01a09e" d="M0 0 l890 0"/>
</svg>

And applying the following CSS to animate the line drawing:

.path2 {
  stroke-dasharray: 1120;
/*   stroke-dashoffset: 800; */
  animation: draw1 5s linear alternate;
}

@keyframes draw1 {
  from {
    stroke-dashoffset: 1120;
  }
  to {
    stroke-dashoffset: 2240;
  }
}

Answer №1

To create this effect, I utilized the canvas element exclusively. The quadraticCurveTo() function was used to form the curved line, while rect() was employed to draw the rectangles.

A crucial aspect of utilizing quadraticCurveTo() is specifying a starting point, necessitating the use of moveTo() before rendering the line.

const canvas = document.querySelector("canvas"),
      ctx = canvas.getContext("2d");
   
// Define first rectangle ("r" represents rectangle)  
let r_x = 20,
    r_y = 20,
    r_width = 80,
    r_height = 30;
    
ctx.beginPath();
ctx.rect(r_x, r_y, r_width, r_height);    
    
// Construct curved line     
let start_x = r_x + r_width*2/3,
    start_y = r_y + r_height,
    point_one = { x: 30, y: 130 },
    point_two = { x: 120, y: 150 };
    
ctx.moveTo(start_x, start_y)
ctx.quadraticCurveTo(
  point_one.x,
  point_one.y,
  point_two.x,
  point_two.y
);

// Define second rectangle
r_x = 80, r_y = 150;

ctx.rect(r_x, r_y, r_width, r_height);

ctx.stroke();
<canvas width="300" height="200"></canvas>

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

What is the best way to implement this design using CSS or JavaScript?

I would like to enhance the appearance of my school website during these challenging times of the pandemic by adding some CSS or JavaScript elements. However, I am unsure how to go about it. ...

What is the best way to display two tables together using inline styling?

I attempted to display 2 tables inline by setting their display property to inline, but unfortunately, it did not work as expected. Is there a more straightforward way to achieve the desired inline display for these tables? table { display: inline; } ...

There was an issue with the Google Maps embed API that resulted in an error with interpolation

My goal is to utilize the Google Maps API in order to showcase a map using data from a JSON file. However, whenever I attempt to incorporate the JSON data, an error message 'Error: [$interpolate:noconcat] Error while interpolating' pops up. < ...

There appears to be an issue with displaying the graph

I am having trouble understanding how to transfer the values entered in the input to the graph that is displayed successfully. Although the update seems correct, nothing changes when I try to update it and the data remains stagnant. Page.vue <script&g ...

How to maintain the side padding of a table within a Bootstrap 4 card?

JSFiddle: Click Here In my design, I have a table within a card element. However, when the window size is reduced to mimic a mobile device, the left padding remains intact while the right padding disappears. How can I ensure that the right side padding is ...

Adjusting the header background color and inserting a logo once a specific threshold is reached

Currently, I am designing a website where I need the background color to transition from transparent to black and display a logo once the user scrolls down to a certain point. I am a beginner in javascript and I am facing some difficulties with this task. ...

How to achieve vertical centering of an image in an li element with fixed dimensions while maintaining 100%

I need help with vertically centering an image within a fixed width and height list item. Here's the HTML I'm working with: <ul class="list"> <li class="list-item"> <div> <img src="http://lorempixel.c ...

Error in connecting Node.js with mongoose

I am working on a Node.js project that involves a MongoDB database and uses Mongoose schema. The project consists of three files: index.js, users.js, and db.js. However, I am encountering an issue when trying to connect to MongoDB using Mongoose. Below is ...

Submitting an mvc partial view form to send data from the parent view

I am currently working on a MVC 5 App where I have a Parent View that includes a Partial View, allowing users to load images. Upon submitting, the Parent view calls a .Ajax function defined within it, which in turn calls a Method/Controller. My requireme ...

Creating a CSS binding for width: a step-by-step guide

I have a complex layout with multiple elements in different divs that need to be aligned. Hardcoding the width or using JS on page load to specify values in pixels both seem like messy solutions. How can I achieve this without causing a zigzag effect? Her ...

Best practices for managing an array of buttons and handling click events in ReactJs

While working on my react class component, I encountered an issue. The alert popup keeps appearing constantly without any button click as soon as the component renders. onHandleOnClick(data, e) { console.log(data); alert("got it" + data); } rend ...

The process of querying two MySQL tables simultaneously in a Node.js environment using Express

My goal is to display both the article and comments when a user clicks on a post. However, I've encountered an issue where only the post loads without the accompanying comments. Here is the code snippet that I've been working with: router.get(&a ...

Optimizing Variable Destructuring Efficiency

Is there a difference in performance when assigning variables like const color = props.color; compared to destructuring like this const { color } = props; Furthermore, does destructuring within the parameters affect performance positively or negatively ...

What is the best way to determine the width of a CSS-styled div element?

Is there a way to retrieve the width of a div element that is specified by the developer? For example, using $('body').width() in jQuery will provide the width in pixels, even if it was not explicitly set. I specifically need to access the width ...

What's causing the "Uncaught SyntaxError: Unexpected token u" error to consistently pop up in Chrome?

I've been trying to figure this out all day by searching online, but I'm still stuck. My code is quite long and runs fine in Firefox, but Chrome throws an error: "Uncaught SyntaxError: Unexpected token u". Could someone please point out where I ...

A guide on adjusting the height of UI elements in Semantic: steps for modifying

One of my current challenges involves using Semantic UI and embedding it within an iFrame tag to display a video. However, I am struggling to adjust the height of the Semantic UI element. <div className="video_box ui embed"> ...

Why are certain items excluded from comparison within a sorting algorithm?

In a scenario where an array of strings needs to be sorted based on multiple criteria, such as copying a list of directory paths, consistency in the result is crucial regardless of the initial order of the input. The following requirements need to be met: ...

Click on the button to sort Angular data

Greetings! I am a newcomer trying to grasp the concepts of angularjs/typescript. I have compiled an array of fruits, displayed in an unordered list. My goal is to arrange them in descending order and implement a reverse search function to display the item ...

Creating a multi-page app using React: A comprehensive guide

I am in the process of developing an application using NodeJS, and I have decided to incorporate React for creating interactive components within the app. However, my goal is to avoid turning it into a single-page application. How can I effectively distri ...

Unable to establish proper functionality of username variables in Node.js chat application

For my latest project, I am developing a chat application in node.js following a tutorial from socket.io. The main objective of the app is to allow users to input their username along with a message, which will then be displayed as "username: message" in t ...