Creating uniform line lengths with a ruler utilizing Fabric.js

I have a div that scrolls horizontally and contains a ruler div and a canvas where I draw horizontal lines of varying lengths.

When drawing the lines, I want to ensure they are accurately measured against the ruler using JavaScript and CSS:

 var canvas = new fabric.Canvas('canvas');

line_length = 14000;

adjusted_length = line_length / 6.367;

canvas.add(new fabric.Line([100, 100, adjusted_length, 100], {
        left: 30,
        top: 50,
        stroke: '#d89300',
        strokeWidth: 2
    }));

    $('#canvas_container').css('overflow-x', 'scroll');
    $('#canvas_container').css('overflow-y', 'hidden');

    drawRuler();


function drawRuler(){
    $("#ruler[data-items]").val(line_length / 200);

    $("#ruler[data-items]").each(function() {
        var ruler = $(this).empty(),
            len = Number($("#ruler[data-items]").val()) || 0,
            item = $(document.createElement("li")),
            i;
            ruler.append(item.clone().text(1));
        for (i = 1; i < len; i++) {
            ruler.append(item.clone().text(i * 200));
        }
        ruler.append(item.clone().text(i * 200));
    });
}

To achieve this, when the line length is different such as 6600, I must adjust the division factor accordingly.

My concern is how to dynamically calculate the length of the line on the ruler based on different line lengths.

You can view the demo at http://jsfiddle.net/dH962/

Answer №1

Figuring that out wasn't overly challenging, all I needed to do was calculate the length of a line measuring 100 pixels on the ruler. The result turned out to be 666 (yes, the infamous number associated with the devil...). Therefore:

adjusted_length = (line_length / 666) * 100;

This formula provides the accurate measurement against the ruler for different line lengths.

You can view a demo at http://jsfiddle.net/Uu4TD/1/

I also rectified an issue with the coordinates while drawing the line...so now:

canvas.add(new fabric.Line([0, 0, adjusted_length, 0], {
        left: 28,
        top: 50,
        stroke: '#d89300',
        strokeWidth: 2
    }));

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 steps can be taken to have Eslint/Prettier report errors and warnings within a CI environment?

Recently, I encountered an issue with my Vue app where I am using Eslint with Prettier. Even though I have set up a Github action to check the code style, running npm run lint -- --no-fix only logs the warnings and does not cause the workflow to fail. I r ...

What's the best way to undo a CSS transition animation when deleting an active class?

I'm currenty working on a straightforward icon animation within a VueJS application. I've implemented a Vue transition to create a fade effect on the background elements, but I'm exploring options for a subtle upward shift animation specific ...

Toggle Divs with jQuery (Rotate images depending on link)

I am currently using the following code to toggle the visibility of div elements. http://jsfiddle.net/XwN2L/3120/ In addition, I would like to have a unique image sprite for each link when it is selected. I attempted to assign individual IDs to each link ...

Using jQuery, the image name will be displayed once it is selected

When I click on the image and then on the Add button, the image name should be displayed in an alert message. However, it is not working as expected. Below is the code that I have tried so far. If I click on the Chocolate image, the alert message should di ...

Implementing Button Activation and Deactivation Upon Checkbox Selection in JQuery

When a single checkbox is selected, the Edit and Delete buttons are enabled while the Add button is disabled. If two or more checkboxes are selected, the Delete button is enabled while the Add and Edit buttons are disabled. This is my HTML code: < ...

How do I iterate through two arrays in jQuery/JS and switch a class using an if/else statement?

Currently, I am iterating over two arrays: selectedLabelsTemp which appears as [1,8], and the rosterLabelList...$(this).data looks like [1,8,2,12]. My objective is to ensure that when it enters the if-else statement, $(this) will receive the class check-ac ...

Troubleshooting the Ineffective Replace Method in React Component

When working in my React component, I have implemented the use of the replace method to substitute a word. However, it seems that this functionality is not generating the expected outcome: const myComponent = () => { const [textVal, setTextVal] = ...

Enhancing the Efficiency of Android Programming

For my application, I am currently displaying 12 markers on a map, each of which triggers a dialog box showing the location's address when tapped. However, I believe there is a more efficient way to handle this. I have been experimenting with creating ...

JavaScript allows users to input an array name themselves

When fetching rows from my database using AJAX, I transform them into an array with a variable identifier. Here is the PHP code: $query_val = $_GET["val"]; $result = mysql_query("SELECT * FROM eventos_main WHERE nome_evento LIKE '%$query_val%&apos ...

When utilizing React router v5, the exact property in a route may not function as expected if there is a

I am attempting to structure routes like Vue.js in an array format: // routes.js export const routing = [ { path: "/setting", component: Setting, }, { path: "/", co ...

Unable to transfer a function to a component using <Route /> tag

In the Erm component, the function setErm is undefined even though it is received by the App component. When passing something like something='foo', the ERM component receives it but not setErm={props.setErm} const App = props => { console. ...

Navigating to a different intent within the DialogFlow Messenger fulfillment can be done by utilizing the 'agent.setFollowupEvent(targetIntentEventName)' method

I am currently exploring ways to initiate another DialogFlow Intent (using its event) from a webhook server built with node.js. This will occur after gathering the user's email address, verifying their registration status by sending a POST API request ...

What causes the lower gap to be smaller than expected when using "top: 50%; translateY(-50%);" on specific elements within the parent container?

My top-bar layout needs to have all elements vertically centered, but I'm experiencing issues with the top-bar_right-part not behaving as expected when using the core_vertical-align class. The left menu works fine, however. To illustrate the problem, ...

Transmit information using jQuery to an MVC controller

I am developing an ASP.NET MVC3 application and need to send three pieces of data to a specific action when the user clicks on an anchor tag: <a onclick='sendData(<#= Data1,Data2,Data3 #>)'></a> Here is the javascript function ...

There was an issue with Angular 2.0 at :0:0, which was caused by a response with status: 0 from the URL: null

I am a beginner in Angular 2.0 and I am currently working on creating a sample application using @angular\cli. To serve the application on my local machine, I use the command ng serve --open, which opens it at localhost:4200. Now, I have developed a ...

Overlapping Bootstrap columns detected when viewing on smaller screens

In an attempt to create a user-friendly layout, I developed two columns: one for the title and another for projects, with the latter being scrollable. The design functions as intended on desktop view but encounters an issue when the viewport is reduced to ...

Showing dummy data in demo mode with an AngularJS table

I stumbled upon this interesting jsfiddle http://jsfiddle.net/EnY74/20/ that seems to be using some demo data. If you check out this example https://jsfiddle.net/vsfsugkg/2/, you'll notice that the table originally has only one row, but I modified it ...

JavaScript Image Swap

I tried implementing this script but it didn't work for me. I'm not sure what to do next, so I'm reaching out for help. The script is at the top of the page, followed by a picture with an id that I'd like to change when a button below i ...

Guide to developing a reusable component or partial in react.js

My first experience with React.js involved a relatively simple task. I started by creating an app.js file that loads the initial page, containing my navigation menu and rendering the children props. However, I realized that instead of keeping the navigat ...

Tips on adding a date range selection or multi-date selection capability within a single Kendo calendar

Can a single Kendo calendar instance incorporate both date range selection and multi-date selection features? ...