Promise not resolving when image onload event is not being triggered

Hello, I've encountered an issue while working with a promise and recursion within a loop. The problem is that the onload event never triggers, causing the promise not to resolve as expected.

Could someone please review my code and point out any mistakes I might be making?

function imageResizeToDataUriPromise(url, width, height) {

    return new Promise(function (resolve, reject) {


        var img = new Image();
        img.setAttribute('crossOrigin', 'anonymous');

        img.onload = function () {

             var imgWidth = img.naturalWidth;
             var imgHeight = img.naturalHeight;

             var result = _scaleImage(imgWidth, imgHeight, width, height, true);
             //create an off-screen canvas
             var canvas = document.createElement('canvas');
             var ctx = canvas.getContext('2d');

             canvas.width = result.width;
             canvas.height = result.height;

             //draw source image into the off-screen canvas:
             ctx.drawImage(img, 0, 0, result.width, result.height);

            resolve(canvas.toDataURL());

         };

        img.src = url;

    });
}

Answer №1

Here is a simple block of code that I have been using, but it seems to be stuck in a loop

caller(logo, 150, 150).then
(function (result) {
  console.log("Great news!", result);
  base64Urls.push(result);

});

Answer №2

After utilizing a promise to retrieve a URL and assigning it to an image element, the functionality is now operational. I am unsure about how the return Data URL would be utilized. One potential concern could be: have you verified if your image source is providing you with the image? (double check the network tab in developer tool).

function imageResizeToDataUriPromise(url, width, height) {

  return new Promise(function(resolve, reject) {
    var img = new Image();
    img.setAttribute('crossOrigin', 'anonymous');

    img.onload = function() {
      console.log("IMG ONLOAD handler invoked");
      var imgWidth = img.naturalWidth;
      var imgHeight = img.naturalHeight;

      var result = img;

      //create an off-screen canvas
      var canvas = document.createElement('canvas');
      var ctx = canvas.getContext('2d');

      canvas.width = result.width;
      canvas.height = result.height;

      //draw source image into the off-screen canvas:
      ctx.drawImage(img, 0, 0, result.width, result.height);

      ctx.fillStyle = "white";
      ctx.font = '21px sans-serif';
      ctx.fillText('Hello world', 21, 51);

      resolve(canvas.toDataURL());
    };

    img.src = url;

  });
}

imageResizeToDataUriPromise("https://i.imgur.com/j7Ie7pg.jpg", 100, 100)
  .then(url => document.querySelector("#an-image").src = url);

console.log("Promise obtained");
<img id="an-image">

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

Trouble fetching the concealed field data within the MVC framework

Upon executing the code provided below on an ASP.NET web form, I noticed that the value of the hidden field customerDeviceIdReferenceCode appears in the page source. <div id="customerDeviceIdReferenceCode" style="display:none;"> <inpu ...

Using .val() in JSON while Html.DropDownList variable is null

I'm having trouble retrieving the value of an item from a dropdown list and passing it to the controller using an ajax post. No matter what I try to pass, it keeps coming back as null. Dropdown List: <div class="form-inline"> @Html.DropDow ...

Accessing node postgres and fetching combined fields with duplicate names

Currently, I am developing a node.js application that utilizes the pg package to connect to a PostgreSQL database. The problem I am encountering involves querying data using a join statement and finding that fields from one table overwrite those from anoth ...

Unravel the JSON structure

Here is the JSON response I received from an AJAX call: [{"id":null,"period":null,"until":null,"agent_id":"15","agent_zlecajacy_id":"15","offer_id":null,"status":"1","tytul":"Pobranie ksi\u0105g","tresc":"Pobranie ksi\u0105g","data_aktualizacji" ...

Is there a way to trigger an Angular $scope function from a hyperlink in the current or a new tab using a right

Here is the HTML code I am working with: <a href="" ng-click='redirectToEntity("B-",obj.id")'>Click me and Process function and then redirect</a> While this code successfully processes the function and redirects to the desired page ...

Guide to Implementing the GitHub Fetch API Polyfill

I'm facing an issue with making my code compatible with Safari by using the GitHub Fetch Polyfill for fetch(). I followed the documentation and installed it using: $ npm install whatwg-fetch --save Although I completed this step, I am unsure of how ...

Capture a snapshot with Protractor using the Jasmine2 Screenshot Reporter

The Protractor configuration file includes 2 custom reporting options: one for logging and the other is the protractor-jasmine2-screenshot-reporter. However, only a blank white screen is displayed when generating a screenshot png. Below is the code snippet ...

"Troubleshooting: Why is the onError event not triggering

Has anyone else experienced issues with using a third-party API to fetch YouTube thumbnails with higher resolution, sometimes resulting in a code 404 error? I've been trying to replace the image source with a default YouTube thumbnail retrieved from i ...

Transforming PHP Variable Using Ajax

I have a variable called $type and I need it to be either month or year. This change should occur when a div is clicked. I attempted to use an onclick event with an ajax call. The ajax call and the variable are both in the same script (index.php). Within ...

When attempting to clear a specific word or character, the entire text is cleared instead

Currently, I am utilizing fabric js along with reactjs to incorporate text onto the canvas. While the text is successfully added, I encountered an issue when attempting to clear specific characters or selected words, resulting in the whole text being cle ...

Is there a way to update a useState in TabPanel without causing a re-render?

For the past few months, I've been immersing myself in React and MUI. Recently, I encountered a problem that has me stumped. The Goal: I receive data from a backend and need to display it for users to edit before sending the changes back to the serv ...

Creating a thumbnail with a close button using an image

My code is available at the following link: https://codepen.io/manuchadha/pen/PBKYBJ In this form I have created, I am trying to implement an image upload feature using a file input. The goal is to display a thumbnail of the selected image below the file ...

Gathering the presently unfinished observables within a superior-level rxjs observable

As an illustration, let's consider a scenario where I have a timer that emits every 5 seconds and lasts for 10 seconds. By using the scan operator, I can create an observable that includes an array of all the inner observables emitted up until now: c ...

What is the best way to validate a particular class in javascript?

Need help checking if a specific id has a particular class. Unsure of the process? Here's the code snippet where the attempt at checking the id for a specific class is visible within the homeTransition function. function homeTransition() { ...

An issue arises when attempting to execute npm with React JS

I encountered an error after following the setup steps for a react configuration. Can anyone provide assistance? This is the content of the webpack.config.js file: var config = { entry: './main.js', output: { path:'/', ...

It appears that the JavaScript global dynamic variable is undefined as it changes from function to function, suggesting it might be

I'm encountering an issue with the way these two functions interact when used in onclick calls of elements. Due to external circumstances beyond my control, I need to keep track of when and how elements are hidden. Everything works perfectly as inten ...

Delete the JSON object stored in local storage and reconstruct the array from scratch

I've encountered an issue with deleting an item from LocalStorage...here's the JSON data stored in LocalStorage. { "1461569942024" : {"t_id":1461569942024,"t_build_val":"PreBuild1","t_project_val":"18"}, "1461570048166" : {"t_id":1461570048166 ...

Is there a way to make the submit button navigate to the next tab, updating both the URL and the tab's content as well?

I am encountering an issue with my tabs for Step1 and Step2. After pressing the submit button in Step1, the URL updates but the component remains on tab1. How can I resolve this so that the user is directed to the Step2 tab once they click the submit butto ...

Guide to using the Firefox WebExtensions API to make AJAX requests to the website of the current tab

I am trying to develop a web extension that will initiate an AJAX call to the website currently being viewed by the user. The specific endpoint I need to access on this website is located at /foo/bar?query=. Am I facing any obstacles in using either the f ...

Watching for changes in a callback function - Angular 2

I'm currently working on implementing a callback function within a service class that needs to send data back to the component class. ChatComponent.ts export class ChatComponent implements OnInit { constructor( public _chatService : ChatService) ...