"Looking to enhance your rectangle in fabricjs canvas with some stylish lines? Here's a guide on

Is there a way to insert lines into a rectangle?

For instance, if the rectangle has a height of 90 and I want to include 2 lines, it should look like this, see image here

However, currently it appears like this, see image here

I have two functions - one for creating lines and the other for creating rectangles. When I call the line function inside the rectangle function, the result is not as expected.


addLineToRectangle(){
    console.log("activeObject", this.rect.width);
    for (let i = 0; i < 2; i++) {
        let line = new fabric.Line([0, 100, 90, 100], {
            left: 1,
            top: 30 * i,
            stroke: 'red'
        });
        this.canvas?.add(line);
    }
}

addRect(){
    for (let i = 0; i < 1; i++) {
        this.rect = new fabric.Rect( {
            width: 90,
            height: 90,
            fill: 'transparent',
            stroke: 'blue',
            left: 1,
            top: 90 * i,
        });
        this.canvas?.add(this.rect);
        this.addLineToRectangle();
    }
}

Answer №1

When working with FabricJS, it's worth noting that the Line object has some unique attributes that may lead you to consider using a Polyline instead. With that in mind, here's an updated version of the addLineToRectangle function that I found success with:

addLineToRectangle() {
  console.log("activeObject",this.rect.width);
  for (let i = 1; i <= 2; i++) {
    let line = new fabric.Line([0, 0, 90, 0], {
      left: 1,
      top: 30 * i,
      stroke: 'red',
    });
    canvas.add(line);
  }
}

I made a slight adjustment to your code by starting the loop at 1 instead of 0 and also made a change to the y coordinate of the line to better fit the intended design.

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

Creating synchronous behavior using promises in Javascript

Currently, I am working with Ionic2/Typescript and facing an issue regarding synchronization of two Promises. I need both Promises to complete before proceeding further in a synchronous manner. To achieve this, I have placed the calls to these functions in ...

Ensure that the date is valid using Joi without transforming it into UTC format

Is there a method to validate a date using @joi/date without converting it to UTC? I need to ensure the date is valid before storing it in the database. Here's what I've attempted: const Joi = require('joi').extend(require('@joi/ ...

Encountering an issue with top-level await in Angular 17 when utilizing pdfjs-dist module

While using the Pdfjs library, I encountered an error message that reads: Top-level await is not available in the configured target environment ("chrome119.0", "edge119.0", "firefox115.0", "ios16.0", "safari16.0" + 7 overrides) /****/ webpack_exports = g ...

Displaying Asynchronous Error Messages with the toast.error Function in React

I have successfully integrated an asynchronous login thunk with error handling. While the success message displays correctly, the error message is not appearing as expected. export const loginThunk = createAsyncThunk( 'login', async (credenti ...

Error: Attempting to access 'update' property of a null value

function logUserOut(user: UserInstance) { return user.update({ token: null }); } I encountered an error at this part of the code. Any suggestions on how to fix it? ...

Update the Array object and convert it into a new Array object

I am working with a dynamic Array object this.rating.data = {[4, 1, 8, 3, 3]}; The Array I'm dealing with is this.rating.labels = ["In", "Lo", "Me", "Hi", "Cri"]; There are cases where some data will ...

Is it possible to verify or authenticate the properties received directly from the associated type or interface?

Looking for a more efficient way to handle validation in my component that takes an array of tabs and children as props. I would like to check if the children provided are the same length as the tabs array directly from the type declaration or any cleaner ...

"Enhancing the functionality of @angular/fire by transitioning from version 6.x to 7.x

I need to update my app dependencies and code from @angular/fire 6.x to 7.1.0-rc4 in order to access a feature that is not available in the 7.0.x version. I made the necessary changes in my package.json as follows: "@angular/fire": "~7.1.0-r ...

Should I link my Angular Material 2 data table to AngularFire2 or Firebase service?

Trying to make this work has been quite the struggle. I've spent hours experimenting, but nothing seems to be working as expected. The md data table is relatively new, so there isn't much information available online yet. Connecting Firebase to t ...

Encountered Typescript errors TS1110 and TS1005

Error in TypeScript: typings/node/node.d.ts(83,23): Type expected. TypeScript issue: typings/node/node.d.ts(1830,52): Expected '=' sign. My TypeScript compilation is failing at node.d.ts, despite multiple attempts to reinstall it. ...

Is it possible for Typescript to allow extracted interfaces while excluding properties from another interface?

I've been searching for information on the specific features of this. Despite my efforts on Google, I have been unable to find the details. Any help would be greatly appreciated! interface Numbers { number: number; number2: number; number ...

What is the best way to access an optional field in Typescript without causing errors?

Is there a way to dereference an optional field from an interface in the following scenario? interface Sample { key1?: Array<Obj1> } interface Obj1 { a?: Obj2; } interface Obj2 { b?: string; } const a: Sample["key1"][number][" ...

TSLint throws an error, expecting either an assignment or function call

While running tslint on my angular project, I encountered an error that I am having trouble understanding. The error message is: expected an assignment or function call getInfoPrinting() { this.imprimirService.getInfoPrinting().subscribe( response => ...

Having difficulty specifying the class type in Typescript

I am currently working on defining a 'Definition' type in Typescript. In this case, a Definition could be either a class constructor or an object. Here is the code snippet that illustrates my approach: if (this._isConstructor(definition)) { r ...

Validating patterns in Angular without using a form

Seeking guidance on validating user input in Angular6 PrimeNG pInputText for a specific URL pattern, such as , possibly triggered on blur event. This particular field used to be part of a form but has since been relocated to a more complex 6-part form int ...

Module TypeScript could not be located

Currently, I am in the process of converting my nodejs project from JavaScript to TypeScript. I have updated the file extensions from .js to .ts, but now I am encountering errors with require(). In an attempt to fix this issue, I have added the following c ...

How does Angular capture the generic type of a component?

Having a background in imperative programming languages such as C++, Java, and C#, I am finding it difficult to grasp the concept of generics in Angular components. For instance, let's take a look at the Material datepicker-toggle component available ...

Issues with Angular RxJS handling Firebase JSON data correctly

Currently developing a CMS app, I am using the login button on Google Firebase to test fetching data. Upon using rxjs to properly return JSON data, I encountered an issue where it returns an odd object with some kind of token attached. Seeking assistance o ...

The live updates for user data in Firestore are not being reflected immediately when using valueChanges

Utilizing Angular and Cloud Firestore for my backend, I have a setup where users can follow or unfollow each other. The issue arises when the button text and list of followers/following do not immediately update on the front end after a successful click ev ...

Utilizing Angular-cli and Karma for seamless integration with jQuery

I have scoured the internet and cannot seem to find a solution for my current dilemma, despite it being a widely known issue... Upon running ng test, I am faced with an empty Karma browser: https://i.sstatic.net/VKIHh.jpg Here is what my console display ...