"Utilizing FabricJs with Multiple Canvases to Display the Same Image Repeatedly

Within a loop ranging from 1 to 2, I have created two canvases on the screen and stored them in an object. However, when I load the same two images onto each canvas, only the last canvas displays the images. Why is it not loading on both canvases? Interestingly, there is also a text object that works on both canvases within the same loop.

Take a look at the example code snippet below where images are added only to the second canvas while the text object is successfully added to both canvases:

var canvases = {};
var imageUrls = ['url here', 'url 2 here'];

for(var p = 1; p <= 2; p++){
    canvases[p] = new fabric.Canvas('canvas-element-' + p);
    var t = new fabric.Text('Testing', {top:600, left:0});
    canvases[p].add(t);
    canvases[p].renderAll();
    
    for(var i in imageUrls){
        fabric.Image.fromUrl(imageUrls[i], function(img){
            img.set({
                width:500,
                height:500,
                top:0,
                left:0
            });
            canvases[p].add(img);
            canvases[p].renderAll();
        }
    });
}

Answer №1

  1. imageUrls array is structured with images at positions 0 and 1, but the access should be made to positions 1 and 2.
  2. fabric.Image.fromUrl function should actually be fabric.Image.fromURL

  3. The loading of the image is done asynchronously, so it's advisable to enclose it in a self-invoking function or use let in the for loop as follows:

    for (let p = 1; p <= 2; p++) {

var canvases = {};
var imageUrls = ['', 'https://via.placeholder.com/300x300?text=canvas1', 'https://via.placeholder.com/300x300?text=canvas2'];
for (var p = 1; p <= 2; p++) {
  canvases[p] = new fabric.Canvas('canvas-element-' + p);
  var t = new fabric.Text('Testing', {
    top: 600,
    left: 0
  });
  canvases[p].add(t);
  canvases[p].renderAll();
  (function(index) {
    fabric.Image.fromURL(imageUrls[p], function(img) {
      img.set({
        width: 500,
        height: 500,
        top: 0,
        left: 0
      });
      canvases[index].add(img);
      canvases[index].renderAll();
    });
  })(p);
}
canvas{
 border :2px solid #000
}
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.js"></script>
<canvas id='canvas-element-1' width=300 height=300></canvas>
<canvas id='canvas-element-2' width=300 height=300></canvas>

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

Is there a way to manipulate text in JQuery without altering the inner element?

I am struggling with an issue in my HTML code. Currently, I have the following structure: <h3 id="price">0.00<sup id="category">N/A</sup></h3> My intention is to use AJAX to replace the content within the <h3 ...

Include jQuery from a different directory

A Closer Look at the Symptoms Encountering issues with jQuery file paths can lead to undefined errors. With jQuery located in different directories, such as the root or child directory, certain JavaScript files may fail to recognize its presence. The sol ...

Is there a correct way to properly duplicate a JSON array in Redux?

As a newcomer to Redux, I found the concepts somewhat confusing at first. For instance, imagine that there is an array in the redux state. const state = [ {show: false, id : '1'}, {show: false, id : '2'}, {show: false, id : &apo ...

How can we extract word array in Python that works like CryptoJS.enc.Hex.parse(hash)?

Is there a method in Python to convert a hash into a word array similar to how it's done in JavaScript? In JavaScript using CryptoJS, you can achieve this by using: CryptoJS.enc.Hex.parse(hash), which will provide the word array. I've searched ...

Tips for inserting information into data tables

Let me begin by outlining the process I am undertaking. I interact with a remote JSON API to retrieve data, perform some basic operations on it, and ultimately produce a data row consisting of three variables: Date, name, and message (think of an IRC chat ...

Tips on implementing v-show within a loop

Hey @zero298, there are some key differences in the scenario I'm dealing with. My goal is to display all the items in the object array and dynamically add UI elements based on user input. Additionally, v-if and v-show function differently (as mentione ...

Having trouble with your JavaScript regex not functioning properly?

I am currently working with an array of arrays and I need to iterate through it to retrieve each word, excluding any "@", punctuation, and hashtags. However, my regular expression seems to be removing certain words entirely from the array and I can't ...

Locate a button element and dynamically assign an identifier using jQuery or JavaScript

I am currently working on a webpage that contains two forms, both enclosed within a <DL> element. <dl> <form action="" method="POST" style="display:inline-block;"> <dl><dt></dt><dd><input class="submit" typ ...

Ways to reset input fields following form submission

I've been trying to figure out how to clear the input fields once the form is submitted, but for some reason, the input data remains there even after each submission. I'm using ajax jquery form. Any ideas on how to resolve this issue? Thank you ...

Loading objects with textures in Three.js using the objloader

For the past few weeks, I've been diving into Three.js and managed to successfully apply a texture to a cube I created directly in the code. However, when I attempted to load an OBJ file using OBJLoader, I ran into issues trying to load simple png or ...

`Inconsistencies between Postman and AngularJS service responses`

When I make a call to the endpoint using Postman, I receive this response: https://i.stack.imgur.com/pH31G.png However, when I make the same request from my AngularJS service defined below: this.login = function (loginInfo) { return $http({ ...

How can the issue of v-slot missing in Vue2.7 be resolved?

After executing the given code, the results displayed are captured in Google Chrome. Below is a snippet of the code used: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-e ...

What is the best method for interacting with multiple links in Puppeteer?

As a beginner with puppeteer, I am diving into the world of web scraping by attempting to create a simple scraping task. My Plan of Action The plan is straightforward: Visit a page, Extract all <li> links under a <ul> tag, Click on each < ...

The SCORM content is not establishing a connection with the Learning Management System

Despite initializing, the SCORM package is failing to communicate with the LMS and throwing an error: No SCORM implementation found. Below is my folder structure: -index.php -player.php -course/SCORM-course (directory) -wrap.js -SCORM_2004_APIWrapper.js ...

Correlating Mailgun Webhook event with Mailing list email

Recently, I have started using the Mailgun API to send emails and have also begun utilizing their mailing list feature. When sending to a mailing list, such as [email protected], I receive a single message ID. However, when receiving webhook responses, t ...

Tips for ensuring the accurate retrieval of prop values by waiting for the value to be set

Encountering an issue with the .toUpperCase() method within one of my components, resulting in the following error: TypeError: Cannot read properties of undefined (reading 'toUpperCase') This problem seems to stem from a race condition in fetc ...

The final output message from the NPM package is displayed right at the conclusion

Is there a way to add a log message at the end of the npm install process? To enable CLI tab autocompletion run: mypackage completion >> ~/.profile <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d5a5a7bab2a7b0a6 ...

The object does not contain a 'navigation' property within the 'Readonly<{}> & Readonly<{ children?: ReactNode; }>' type

As a beginner in react native, I am facing some challenges with the components I have created. Let me share them: List of Playlists: export default class Playlists extends Component { playlists = [ ... ]; render() { const {navigation} = th ...

Connect the front end files, including HTML, CSS, and JavaScript, to the Node.js backend

I'm a beginner in web development and recently completed an online course on node.js and express. However, the course didn't cover how to add HTML, CSS, and JS files when using Node. I attempted the following: var express = require('expres ...

Using Material UI Autocomplete for Categorical Selections in a ReactJS Application

Using MUI Autocomplete and Formik, I'm looking to organize items into categories. If an item doesn't have any sub_accounts, then it should not display a header label. Check out the example here: https://mui.com/material-ui/react-autocomplete/#gro ...