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

Jssor's dynamic slider brings a touch of sophistication to preview upcoming images

Incorporating the jssor nearby slider to create a nearly fullscreen display. The goal is to set the opacity of upcoming images to 0.25 when they are not in the main viewport, giving the edges of the upcoming and previous slides a slight transparency. < ...

Utilize the splice function when resizing the window based on specific breakpoints

On a series of div elements, I have implemented some JS/jQuery code that organizes them by wrapping every three elements in a container with the class .each-row. <div class="element"></div> <div class="element"></div> <div class ...

A straightforward interval-based Ajax request

I've recently delved into the world of Ajax and jQuery. Just yesterday, I embarked on creating a simple ajax request for a form that sends a select list value to a PHP script and retrieves data from a database. Things are going smoothly so far! Howev ...

Automate the input provided to yeoman command line interface for implementing CI/CD tools

When executing Yeoman, it prompts for input one by one. Is there a way to provide all inputs at once or programmatically? For instance: yo azuresfguest It requests 5 inputs to be added, which I would like to provide in one go for running in a CI/CD syst ...

Retrieve an image from the server and display a preview of it on the client side

I'm currently in the process of fetching an image from a server and previewing it on the client side. I have successfully retrieved the image, but I am unsure of how to asynchronously display it on a web page. axios.get(link,{responseType:'strea ...

Achieving success was like uncovering a hidden treasure chest after a successful

Is there a way to address this JSON data issue? success{"data": [{"id":"1","name":"something1"},{"id":"2","name":"something2"},{"id":"3","name":"something3"}] } The success variable contains the JSON data. This is how the server script returns the data: ...

Is there a more efficient method to execute this AJAX request?

$('#request_song').autocomplete({ serviceUrl: '<%= ajax_path("trackName") %>', minChars:1, width: 300, delimiter: /(,|;)\s*/, deferRequestBy: 0, //miliseconds params: { artists: 'Yes' }, onSelect: functi ...

Optimizing Chrome's Precious Load Time

Encountering issues with Chrome browser auto-filling passwords, usernames, etc. Creating a problem where input field validation for emptiness is not possible in Chrome while it functions correctly in other browsers. $(document).ready(function() { ...

Is there a method to prevent the json file from being constantly overwritten?

After running this code, I noticed that even when inputting a different userId, it still ends up overwriting the existing user instead of adding a new one as intended. const user = userId; const userObj = {[user]:valueX}; words.users = userObj; f ...

What are the steps involved in incorporating a REST API on the client side?

Hey there! Today I'm working with a simple Node.js express code that functions as a REST API. It works perfectly when I use Postman to send requests with the GET method, as shown in the code below. However, when I try to implement it on the client sid ...

Data will not bind with Laravel and Vue

I am currently working on a Laravel project and trying to develop a basic editing feature for posts. My approach involves using Vue.js 2 to bind the data, but unfortunately, I am facing issues with displaying it - I'm not quite sure what's causin ...

Executing functions in a pre-defined order with AngularJS: A step-by-step guide

In my AngularJS Controller, I have a receiver set up like this: // Broadcast Receiver $rootScope.$on('setPlayListEvent', function(event, playListData) { if($scope.someSoundsArePlaying === true) { $scope.stopAllS ...

How can I showcase data retrieved from a function using Ajax Datatable?

I have implemented an Ajax function that retrieves data from a PHP file and displays it in a DataTable. Initially, this setup was working fine. However, when I added a new function to the PHP file, my Ajax function stopped retrieving data from the file. I ...

Best resolutions and formats for Nativescript-Vue application icons

I'm a newbie when it comes to Nativescript, and I'm looking to change the icon for my app. After doing some research, I found this command: tns resources generate splashes <path to image> [--background <color>] This command seems li ...

React Redux - There is an error during rendering as expected props have not been received yet

After retrieving data from an API and storing it in the Redux state, I utilize a helper function within mapStateToProps to filter and modify a portion of that data before passing it along as props. Although everything appears to be functioning correctly b ...

Having trouble with res.redirect not working after the page has been rendered with data?

I have a basic forget password feature set up, where users can request a password change and receive an email with a token. Clicking the link in the email will redirect them to a page where they can input their new password. When I click on the email link ...

Fetching data from the server using Angular and parsing it as JSON

Can anyone provide some insight on the best way to use jsonObjects in ng repeat? Here is my code: This is the response I get from PHP: die(json_encode(array('sts'=>'success', 'title'=>'*****', 'msg' ...

How can PHP be used to decode JSON and transmit it to Javascript?

I am aiming to utilize the Twitter API in order to dynamically populate slides on a webpage with recent tweets without needing to refresh the entire page. Currently, my approach involves making an AJAX call every few seconds from a JavaScript function on ...

When the result of Ajax is identical to that obtained without Ajax, the innerHTML remains the same

I understand that utilizing innerhtml is generally considered a poor practice due to the potential for XSS vulnerabilities (). However, consider the scenario below: I have a webpage generated through a Twig template called index.html.twig. When using te ...

Having an issue with fastify-multer where request.files is coming back as undefined during testing with Postman

In the process of developing an API that consumes multipart/form-data using fastify, I've integrated the fastify-multer plugin to handle file uploads for passing them to another third-party API. Currently, I'm testing with Postman, but encountere ...