Issue encountered with Fabric js: Unable to apply pattern fill to a group of rectangles

Greetings, I am in need of some assistance with a coding issue.

I have a for loop that generates and adds multiple rectangles to a fabric js canvas. To set a texture for each rectangle, I am using the following code snippet.

var rect = new fabric.Rect({
  width: 100,
  height: 100,
  selectable: true,
  hasControls: false,
  borderColor: 'red',
  borderWidth: 2,
  lockMovementX: true,
  lockMovementY: true
});

canvas.add(rect);

fabric.util.loadImage('construct/css/img/patterns/1.jpg', function(img) {
  rect.set('fill', new fabric.Pattern({
    source: img,
    repeat: 'repeat'
  }));
});
 Execute 

After running the code, only the last rectangle added has a texture applied, while the others do not.

This situation is truly frustrating me.

Any help on this matter would be greatly appreciated.

Thank you in advance.

Answer №1

It seems like you are using the variable 'rect' for all your rectangles, which may be causing the pattern only to apply to the last object created.

A scenario where you add 4 rectangles:</p>
for (var i = 0; i < 4; i++){
    var rect = new fabric.Rect({
    width: 100,
    height: 100,
    left: i * 110,
    selectable: true,
    hasControls: false,
    borderColor: 'red',
    borderWidth: 2,
    lockMovementX: true,
    lockMovementY: true
  });

  canvas.add(rect);
}

To apply a fill pattern to all rectangles, you will need to loop through each one and set the fill pattern using:

fabric.util.loadImage('http://fabricjs.com/lib/pug.jpg', function(img) {
    canvas.forEachObject(function(obj){
    obj.set('fill', new fabric.Pattern({
    source: img,
    repeat: 'repeat'
  }));
  });
  
  canvas.renderAll();
});

You can find the working code here

NOTE: If there are other objects besides rectangles, make sure to ignore them by checking their type or defining a custom shape type for the rectangles.

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

The option chosen from the ng-options does not remain attached to the drop-down menu

I need some help with AngularJS as I am still getting the hang of it. Take a look at this not-so-pretty page: This page allows users to add new beers, and each beer can have multiple styles. Clicking 'Add' creates a new dropdown for selecting a ...

When calling a function within a for loop, the function receives the final value instead of iterating through the sequence

I need assistance with setting unique names for objects in an array. I have the following setup: this.array = [{name: null}, {name: null}, {name: null}] Along with a list of reserved names: this.reserved = ["name2", "name3"] My goal is to loop through th ...

"Having issues with Django not properly applying the JavaScript and CSS files I've linked in

I have completed my project and organized all the necessary files, including index.html, css, js, and settings.py within the appropriate folders. I am encountering an issue with applying a pen from the following source: CodePen index.html <!DOCTYPE h ...

A declaration of "import '***.css';" was located within an ECMAScript module file in the monaco-editor npm library

It's perplexing to me why the developers of monaco-editor included these statements, as they are actually causing errors in my browser such as: Failed to load module script: Expected a JavaScript module script but the server responded with a MIME typ ...

The image will remain static and will not alternate between hidden and visible states

I am facing a challenge trying to toggle an image between 'hidden' and 'show' My approach is influenced by the post on How to create a hidden <img> in JavaScript? I have implemented two different buttons, one using html and the ...

Passing props from pages to components in NextJS: A guide

My nextjs-application has a unique folder structure: components -- layouts --- header.tsx --- index.tsx pages -- index.tsx -- [slug].tsx In the [slug].tsx file, I utilize graphql to fetch data and set the props accordingly: export default ...

Issue with Angular controller not refreshingalternatively:Angular

I just started reading an AngularJS book by O'Reilly and I encountered a problem with the first example. Instead of seeing "hello" as expected in place of "{{greeting.text}}", it displays exactly that. I have double-checked my angular linking and even ...

The Slide Out Menu functioned properly in HTML, but it seems to be malfunctioning when implemented in PHP

I recently implemented a slide-in and out menu with a hamburger icon to open it and an X icon to close it. The functionality was perfect until I integrated it into PHP and WordPress. Initially, I placed the script in the header section before the meta tags ...

Enhance your Vue.js application by dynamically adding a class when a computed value

Just delving into the world of vue.js and I have a simple query. I've been following a tutorial but now I'd like to add my own touch to it :-P Whenever there is a change in my rank, I would like to include a CSS class for animating the label. Ho ...

TypeScript's type assertions do not result in errors when provided with an incorrect value

We are currently using the msal library and are in the process of converting our javaScript code to TypeScript. In the screenshot below, TypeScript correctly identifies the expected type for cacheLocation, which can be either the string localStorage, the ...

Error in Vue.js: Trying to access properties of an undefined object

My understanding of vue.js is limited, but based on what I know, this code should work. However, when attempting to access the variable in the data property, it seems unable to locate it. data: function() { return { id: 0, clients: [] ...

Can you explain the reference point used in the `drawImage()` function on a canvas?

Here is an inquiry concerning the usage of the drawImage() function. var x = (i-j)*(img[0].height/2) + (ctx.canvas.width/2)-(img[0].width/2); var y = (i+j)*(img[0].height/4); abposx = x + offset_x; abposy = y + offset_y; ctx.drawImage ...

Error: 'error' is undefined

Error Alert: The code is encountering a ReferenceError, indicating that 'error' is not defined in the following snippet: app.post('/register', function(req, res) { var hash = bcrypt.hashSync(req.body.password, bcrypt.genSaltSync(10)) ...

A method to efficiently send multiple axios GET requests by incrementing the URL parameters

Is there a way to efficiently send multiple HTTP GET requests using Axios? For instance: let maxRequests = 3000; let currentRequest = 0; do { currentRequest = currentRequest + 1; await response = axios.get(`https://example.com/${currentRequest}` ...

How to transfer identification from one AngularJS page to another

I need help figuring out how to retrieve an ID from the list.html page and use that same ID to display corresponding details on the list-detail.html page. I am new to using angularjs and struggling with getting the details based on the ID. Below is my code ...

Can someone clarify the distinction between returning a value directly or using Promise.resolve within the then() function?

What is the distinction between: new Promise(function(res, rej) { res("first example"); }) .then(function(result) { return "bbb"; // directly returning string }) .then(function(result) { console.log(result); }); and this: n ...

Sort through a collection of objects depending on various criteria pulled from a separate array of objects

I am working with an array of objects called c, which looks like this: c = [ { name: 'abc', category: 'cat1', profitc: 'profit1', costc: 'cost1' }, { name: 'xyz', catego ...

Where is the location of the directory on the hard drive that was created using the getDirectory() method in HTML5?

I have been working on creating, deleting, and reading directories but I am unsure of where they are located on the hard drive. fs.root.getDirectory('something', {create: true}, function(dirEntry) { alert('Congratulations! You have succes ...

Utilize JavaScript to communicate with the backend server

I'm embarking on my first Cordova application, utilizing HTML, CSS, and JavaScript. My current objective is to trigger a local server call upon button click, with the intention of logging something to confirm functionality. However, I'm encounter ...

Navigating production mode in nuxtjs and uncovering errors

There seem to be numerous inquiries regarding this matter. Unfortunately, there doesn't appear to be a definitive solution. Is there any way to view detailed error logs in production mode? https://i.stack.imgur.com/prXUt.jpg ...