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

Dynamic animations with RaphaelJS - Creating animated connections

I recently came across a similar project here: My current project involves animating boxes by clicking a button. While I am able to move the boxes around smoothly during animation, the issue is that the connections between them do not move along. Is there ...

What is the best way to display the data model in Angular as HTML?

I am facing an issue with my data-model where it needs to be converted or displayed as HTML, but currently it is only appearing as plain text. Here is the HTML code snippet: <div ng-repeat="item in ornamentFigures" class="ornament-item"> <la ...

Using an array as a reference can lead to failure when dealing with asynchronous calls

As I delve into referencing a document in MongoDB, my process involves first creating the document to insert before interfacing with the database itself. Upon initial setup: const venues = [ new Venue({ name: 'A' }), ]; const events = [ new ...

CSS - Customizing the appearance of consecutive child divs

I'm struggling with adjusting the margin between two child divs when they follow each other. The current margin is set at 3rem, but I want it to be 1rem if both child containers have the class "narrow": Is there a way to achieve this without changing ...

Issues with jQuery draggable functionality in Ruby on Rails 3.1

I created a new RoR 3.1 project to experiment with this feature. To enable draggable functionality, I included the necessary jQuery .js files in my app/assets/javascripts directory: jquery.ui.core.js jquery.ui.widget.js jquery.ui.mouse.js jquery.ui.dragga ...

Is there a way to retrieve the file path of the file that is imported using an alias in Vite (Vue3)?

Hello! I have a few inquiries. Is it feasible to obtain the file path of the file utilizing an alias for import in Vite (Vue3)? Setup Here's the directory structure I'm using, purely for illustrative purposes: src/ module_a/ some_ ...

Is it possible to use JavaScript to save and preserve the current state of a webpage?

I'm looking for a way to retrieve the entire content of a webpage using JavaScript and then send it to a server script for saving. This action should be triggered after the user has made some changes to the page using AJAX and other JavaScript tools. ...

Incorporating type declarations for a basic function that returns a wrapper function for other functions

In my vanilla JS code, I have a sophisticated function that is exported and I am attempting to create a .d.ts file for it. Unfortunately, my previous attempts at writing the .d.ts file have not been successful in passing the types from one stage of the fu ...

Choose CSS Option

I need assistance with customizing my dropdown select option - see the example below <select> <option value="volvo" title="NEED THIS BIGGER AND FORMATED" >Volvo</option> <option value="saab">Saab</option> <option val ...

What is the best way to modify the underline style of a tab in Material UI?

I'm trying to customize the underline of: https://i.stack.imgur.com/J2R1z.png Currently, I am using material ui version 4.12.3 The code snippet for generating my tabs is below: function renderTabs(): JSX.Element { return ( <Tabs className={cla ...

Prevent horizontal HTML scrolling while displaying a layer

I am currently working with a .layer div element that darkens the page to highlight a modal. However, I have encountered an issue where upon triggering the event, the div does not occupy 100% of the screen and the original browser scroll bar disappears. I ...

Modify the location of the input using jQuery

Hey there, I've got this snippet of HTML code: <div class='moves'> <div class='element'><input type='text' value='55' /></div> <input class='top' type='text&apo ...

Tips for eliminating repetitiveness in situations such as BEM modifiers

As I delved into using my own adaptation of the BEM methodology, I encountered a roadblock with modifiers for nested elements. The challenge at hand is changing the link color to red when product-desc-name has the mark class. The snippet below illustrat ...

React - Utilizing Secondary Prop Value in Material UI Node Components

I've been working on streamlining my code and am wondering about the best way to pass an additional value using props while fetching data from the backend. I'm utilizing material UI's Autocomplete with the PERN stack. Everything is functioni ...

Tips for accessing another page when location.state is missing

In my react application, I am passing state through react router and accessing it in the target component/page using the location object. Everything works perfectly fine initially, but when I close the tab and try to open the same page by pasting the URL i ...

How to Assign a Specific ID to the Body Tag in Wordpress Using functions.php

Struggling to find a simple solution after scouring the web for answers. Most tutorials are overly complicated. I'm attempting to integrate a jQuery menu system into my Wordpress site and want to assign a unique body ID to make targeting easier. I p ...

Creating a personalized gradient using Tailwind CSS and Daisy UI framework

I’m attempting to incorporate a unique gradient into my next.js application with the help of Tailwind CSS and Daisy UI. Below is the specific code snippet I plan on using: background: linear-gradient(180deg, rgba(192, 192, 192, 0.04) 0%, rgba(201, 180, ...

Unable to stop interval in Angular 5 application

My setInterval() function seems to be working fine as the timer starts, but I am encountering an issue with clearInterval(). It does not stop the timer when the counter value reaches 100 and continues running continuously. Any help or suggestions would be ...

The surprising margins that Bootstrap sneaks into columns

It seems like bootstrap is mysteriously including an unseen margin in my column classes. Even after inspecting an element labeled as 'col-lg-3,' there is no visible margin CSS, and attempting to manually add margin:0 still results in a margin bei ...

Unable to modify the appearance of an HTML element when injected via a Chrome extension

I am currently developing a unique chrome extension that uses Ajax to inject custom HTML into the current tab. This extension appends a <div> element to the body, and now I need to manipulate it using JavaScript. Specifically, I want it to dynamical ...