Achieving consistent alignment for text on a curved path

I am working on a unique "flow-builder" project and I need to achieve this specific result: https://i.sstatic.net/6TTuS.png

At the moment, my current edge looks like this: https://i.sstatic.net/9ydzx.png

The text on the edge is currently aligned with the edge itself, however, I need it to align differently as shown in the first image

Since I am new to path/textPath, I am struggling to figure this out. Here is the code snippet for my "Edge" component:

import React from 'react';
import { getSmoothStepPath, getMarkerEnd } from 'react-flow-renderer';

export default function DefaultEdge({
                                       id,
                                       sourceX,
                                       sourceY,
                                       targetX,
                                       targetY,
                                       sourcePosition,
                                       targetPosition,
                                       style = {},
                                       data,
                                       arrowHeadType,
                                       markerEndId,
                                   }) {
    const edgePath = getSmoothStepPath({ sourceX, sourceY, sourcePosition, targetX, targetY, targetPosition });
    const markerEnd = getMarkerEnd(arrowHeadType, markerEndId);

    return (
        <>
            <path id={id} style={style} className="react-flow__edge-path" d={edgePath} markerEnd={markerEnd} />
            <text>
                <textPath href={`#${id}`} style={{ fontSize: '12px' }} startOffset="90%" textAnchor="middle" >
                    {data?.text  || 'default text'}
                </textPath>
            </text>
        </>
    );
}

Answer №1

Assuming you are working on a canvas since you tagged canvas, I won't be able to assist with the provided code but can give you an example of how to utilize canvas's built-in methods to achieve your desired outcome.

let canvas = document.getElementById("canvas");
let ctx = canvas.getContext("2d");
canvas.width = 300;
canvas.height = 300;

let pt1 = {x: 50, y: 50};
let pt2 = {x: 200, y: 50};
let pt3 = {x: 230, y: 150};
let pt4 = {x: 230, y: 220};
let pt5 = {x: 230, y: 250};

let nodes = [];
class Nodes {
  constructor(x, y) {
    this.x = x;
    this.y = y;
    this.r = 5;
  }
  draw() {
    ctx.beginPath();
    ctx.arc(this.x, this.y, 5, 0, Math.PI*2);
    ctx.fill();
  }
}

let node1 = nodes.push(new Nodes(pt1.x, pt1.y));
let node2 = nodes.push(new Nodes(pt3.x, pt3.y));
let node3 = nodes.push(new Nodes(pt4.x, pt4.y));
let node4 = nodes.push(new Nodes(pt5.x, pt5.y));

for (let i=0;i<nodes.length;i++) {
  nodes[i].draw();
}

class Edge {
  constructor(x, y, lw) {
    this.x = x;
    this.y = y;
    this.lw = lw;
  }
  draw() {
    ctx.strokeStyle = 'black';
    ctx.beginPath();
    ctx.moveTo(pt1.x, pt1.y);
    ctx.lineTo(pt2.x, pt2.y);
    ctx.bezierCurveTo(230, 50, 230, 50, 230, 80);
    ctx.lineTo(pt3.x, pt3.y);
    ctx.moveTo(pt4.x, pt4.y);
    ctx.lineTo(pt5.x, pt5.y);
    ctx.stroke();
  }
}

let edge1 = new Edge();

edge1.draw()

ctx.font = 'bold 20px arial';
ctx.textAlign = 'center';
ctx.textBaseline = "middle";
ctx.fillText('Hello world', pt3.x, (pt3.y + pt4.y)/2);
<canvas id="canvas"></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

Is a fixed div located inside a fluid grid container?

Having developed a website with a fluid 12 column grid, I am looking to lock the position of a div in the right hand column once it reaches the top of the page (using something like StickyJs or a similar tool). However, when the fixed position is applied, ...

Achieving right to left direction in react-bootstrap: Tips and Tricks

Seeking to create a react UI with a right-to-left (RTL) direction has proven challenging. Attempting to achieve this using bootstrap className="pull-right" or manually adjusting CSS properties like *{direction:rtl;} and .float-right:{float:right;} on react ...

Modifying the active NavLink in Reactstrap with onClick event handler

Is there a way to easily switch between active tabs? This code snippet shows 'Link 1' as the default active tab. const Navi = () => { const startChangeVis = id => { // Implement logic here to set clicked NavLink as active } r ...

Easy steps to eliminate background color from text

https://i.sstatic.net/mKmIW.png I have encountered an issue where a white background is covering the background image in my coding project. Despite trying to add background-color: transparent;, I wasn't able to remove the white background. How can I r ...

What is the best way to utilize the properties obtained from a spread operator?

I am encountering a confusing issue in my code. I am passing an object as a prop and then taking it as a param. Passing props Taking it as a param Console logging the prop Initially, everything works as expected. However, when I use the spread operato ...

Installing NPM with the mysterious -E prefix, completely unfamiliar

During the installation of the MATERIAL TAILWIND package, an unfamiliar notation caught my attention in the npm command: npm i -E @material-tailwind/react I'm curious to know what this -E stands for. Any insights would be greatly appreciated. Thanks ...

How to effectively manipulate nested arrays in JavaScript without altering their references

Welcome everyone, I've been working on a project using next.js and I've encountered an issue with filtering posts. The filter function works perfectly when the posts are in a simple array like ObjChild. However, I have another section on my site ...

Animate the service item with jQuery using slide toggle effect

Currently, I am working on a jQuery slide toggle functionality that involves clicking an item in one ul to toggle down the corresponding item in another ul. However, I am encountering difficulties in linking the click event to the correct id and toggling t ...

An error occurred while trying to load the resource in the Redux-Saga: connection refused

Utilizing axios allows me to make calls to the backend server, while redux-saga helps in managing side effects from the server seamlessly. import {call, put, takeEvery} from "redux-saga/effects"; import {REQUEST_FAILED, REQUEST_SUCCESS, ROOT_URL, SUBMIT_U ...

Cross-origin resource sharing (CORS) policy issue arises when the 'Access-Control-Allow-Origin' header is not included in the requested resource, especially when utilizing an iframe in a React

I am trying to link a website to a button using an iframe. This website allows access to all domain names. Below is the code for my button: <Button component={NavLink} activeClassName={classes.activeBtn} to="/searchEngine&qu ...

Enhancing functionality with extra JavaScript tags in next.js

Recently, I delved into programming with react & next.js after previously working with node.js. It didn't take long for me to create my first application, but upon inspecting the page, I noticed an abundance of extra JavaScript code (see image below). ...

The issue of webkit animation rotation malfunctioning on Nexus Mobile devices

I'm currently working on developing a double ring radar animation within an Ionic hybrid application. The animation functions perfectly when viewed in a web browser, however, I've encountered issues when attempting to run it on the Nexus mobile ...

Adjust the maximum and minimum values on a dual thumb slider

I have implemented a two thumb range slider to define the maximum and minimum values. However, I recently discovered that it is possible for the thumbs to cross over each other - the max value can exceed the min value and vice versa. I am looking for a s ...

Using useNavigate outside of a React hook: What you need to know

This code retrieves a list of emails from Firestore and verifies if the current user is registered. If the user is new, it redirects them to the sign-up page. The functionality works correctly as it redirects successfully, but an error message appears: W ...

What happens when the reducer is operating with the initialState in place?

Here is a code snippet taken from an online course: import * as PlayerActionTypes from '../actiontypes/player'; const initialState = [ { name: 'Jim Hoskins', score: 31, }, { name: 'Andre ...

Looking to have the image float after reducing the size of the windows in html?

For my webpage, I want an image to appear on the extreme left when the browser is maximized, but then move to the extreme right when the browser is minimized. I've tried using float, but it doesn't seem to be working. Any suggestions on how to ac ...

Step-by-step guide to creating a border around text with a number included in between the lines

Is there a way to replicate the appearance of the image shown below using CSS, Bootstrap, or other client-side methods? ...

Tips for adjusting column positions in a table while maintaining a fixed header and utilizing both horizontal and vertical scrolling

Is there a way to display a table that scrolls both horizontally and vertically, with the header moving horizontally but not vertically while the body moves in both directions? I have been able to shift the position of the columns, however, I am struggling ...

Tips for displaying NoOptionsText in MaterialUI Autocomplete based on a specific condition

When using a Material UI autocomplete feature, the items are selected based on the first 3 letters typed. For example, if you're searching for all "Pedros" in your database, typing "Ped" will bring up results starting with those letters. The issue ar ...

Encountering difficulties resolving the dependency tree while trying to install @react-navigation/[email protected]

After creating a new project called MyProject using react-native init MyProject, I opened it in VSCode and the first task was to install navigation. Initially, when running npm install @react-navigation/native @react-navigation/stack, it threw an error. S ...