Tips for waiting on image loading in canvas

My challenge involves interacting with the image loaded on a canvas.

However, I am uncertain about how to handle waiting for the image to load before starting interactions with it in canvas tests.

Using driver.sleep() is not a reliable solution. Here is a snippet of code from the page that includes a canvas element:

<canvas class='ol-unselectable' width='816' height='400' style='width: 100%; height: 100%;'></canvas>

The application is Angular-based.

Looking at the Network tab in the developer console, I can see that there is an Img request during the image loading process.

I believe there may be a way to write some code that checks if the image has loaded into the canvas and then use it through JavaScript executor.

Unfortunately, I am unsure how to go about it. Any assistance would be greatly appreciated.

Update: I attempted to create a custom waiting condition:

exports.isAllImageLoad = function isAllImageLoad(driver) {
    return new Condition('image loading', function(driver) {
        return driver.executeScript(
            'var img = new Image();' +
            'img.onload = function() { return true; };' +
            'img.onload()'
        ).then(function(result) {
            console.log('image loading: ' + result);
            return result;
        });
    });
};

I tried using it with:

return driver.wait(isAllImageLoad(driver), waitTimeOut);

However, the console shows that the result of img.onload() is null.

Update: I also experimented with the following code:

exports.isAllImageLoad = function isAllImageLoad(driver) {
    return new Condition('image loading', function(driver) {
        return driver.executeScript(
            'var image = new Image();' +
            'function mainLoop(){' +
                'if(image.complete){' +
                    'return true;' +
                '}else{' +
                    'return false;' +
                '}' +
            '}' +
            'mainLoop();'
        ).then(function(result) {
            console.log('image loading: ' + result);
            return result;
        });
    });
};

Yet, the outcome remains the same, returning null.

Answer №1

Here is a different method to avoid waiting for the onload event.

Once the DOM has finished processing the image and it either successfully loads or fails to load, the semaphore image.complete is set to true.

You can utilize this semaphore to decide if it's safe to render the image.

var image = new Image();
image.src = "imageURI";
function mainLoop(){
     if(image.complete){
          ctx.drawImage(image,0,0,100,100);
     }else{
          ctx.fillRect(0,0,100,100); // image placeholder
     }
     requestAnimationFrame(mainLoop);
}
mainLoop();

This approach allows you to continue rendering even while images are still loading.

However, directly determining whether the image has loaded or if there's an error is not possible with this method.

Another option is to create your own semaphore.

var image = new Image();
image.src = "imageURI";
image.onload =  function(){this.ready=true}

Then use the ready semaphore to signal that the image is ready to be rendered.

Answer №2

You should encapsulate your code within the image onload function if you wish to execute it after the image has loaded successfully.

EXAMPLE (displaying an image on canvas after it has finished loading)

var ctx = document.getElementById('canvas').getContext('2d');
ctx.fillStyle = 'black';
ctx.font="50px Arial";
ctx.fillText('Loading...', 300, 200);
var image = new Image();
image.src = 'https://s-media-cache-ak0.pinimg.com/originals/e9/dc/10/e9dc10141d0b4e5c9e360cc5669e65ed.jpg';
image.onload = function() {
  ctx.clearRect(0, 0, 816, 480)
  ctx.drawImage(image, 0, 0);
}
#canvas {
  background-color: lightgrey;
}
<canvas id="canvas" class="ol-unselectable" width="816" height="400" style="width: 100%; height: 100%;"></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

The <a> tag with href attribute is mistakenly identified as an external link when used in conjunction with the <base> tag

I am currently working with jQuery UI tabs using jquery 1.11.1 and jQuery ui 1.11.1. Within the <base> tag in the head>, I have the following: <base href="http://mytestdomain.com/" /> Upon loading the page, jQuery UI creates two tabs from ...

I encountered a console issue that I am struggling with. It is showing the error message "TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'"

When running this code, I encountered an error in the console (TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'). Can someone help me identify where I made a mistake and provide guidance ...

Having trouble choosing options within Material UI's Autocomplete Component?

I'm having trouble selecting the options displayed in MUI's autocomplete component. It seems that using renderOption is causing this issue. I want to show an image along with the title in the component options, but without using renderOption, I h ...

Automated selection menus using Python's Selenium WebDriver for dynamic dropdowns

Just started working with Selenium in Python and I'm facing some challenges with Dynamic dropdowns. One example is on a webpage under the section Subjects and State and City. How can these elements be handled when they are not visible in the DOM? Coul ...

Count the amount of exposed items in each row within a specific container size and dimensions

I created a code sample available at demo code to showcase li elements within a ul displayed in a flow-like manner with the use of display:inline. The challenge I am facing is determining the number of complete li items that are not wrapping for each row ...

Unable to resolve an unresolved issue with a jquery or javascript bug

I am currently facing some issues with my jQuery code in both Firebug and Chrome's developer tools. Any assistance would be greatly appreciated. Kindly make the necessary updates in the provided fiddle. Please follow this link to access the fiddle: ...

Utilize HTML5 Application Cache solely for storing and managing dependencies

My goal is to selectively cache certain files like JavaScript, CSS, fonts, and image sprites. Should I create a manifest file for these specific files or rely on the browser's caching mechanism? If using a manifest is preferred, can I still prevent ...

Is there a way to update the value of a variable with the help of a checkbox?

When I check the checkbox, the specOrder const gets updated as expected. However, I am struggling to figure out how to remove the value when the checkbox is unchecked. Below is the code I have been working on: const SpecialtyBurgers = () => { cons ...

Trigger Function Following Each Digest Cycle Prior to Rendering DOM

Is there a way to run a piece of code after each $digest cycle, once the DOM is built but before rendering occurs? I need this to happen on every $apply, not just those following linking or compiling. Where can I insert my code for this purpose? I prefer ...

Steps to remove a script upon clicking a button?

On my website, I have integrated a plugin called manychat using a <script>. However, when I click on the Drawer Cart, the manychat symbol overlays over the checkout button, which is not visually appealing. Is it possible to unload this script when ...

Utilize a variable within the res.writeHeads() method in Node.js

Greetings all. I have encountered an issue that I need help with: Currently, I am using this block of code: res.writeHead(200, { "Content-Length": template["stylecss"].length, "Connection": "Close", "X-XSS-Protection": "1; mode=block", "S ...

Avoiding Selenium POM and TestNG NullPointerExceptions

I am currently working on automating my tests using web driver, testng, and the page factory. However, I have encountered a null pointer exception while executing the code provided below. HomePage Page Object Class This is the page factory class. packag ...

Is it possible to trigger the JavaScript mouseover function following a click event?

Is it possible to call a function on mouse over after the first click event is triggered by the user? <a href="javascript:void(0);" id="digit<?php echo $k;?>" onClick="javascript:return swapClass('<?php echo strtoupper($v);?>',&ap ...

Upgrade from AngularJS 1.x to the latest version of Angular, AngularJS 2.x

Currently in the process of mastering AngularJS 2 in order to transition my applications from Angular 1.x. The differences between the two versions are quite significant. Can you please share the advantages of upgrading from Angular 1 to Angular 2? I am ...

Understanding how to decode querystring parameters within a Django view

In the application I'm working on, there is a search form that utilizes a jQuery autocomplete plugin. This plugin processes the querystring and sends back the suggested item using encodeURI(q). For example, an item like Johnny's sports displays ...

The attempt to update several partial views using Jquery, MVC, and Json is currently malfunctioning

I am facing issues with updating multiple partial views using jQuery, MVC, and JSON. The partial views on my page are not getting updated. Below is the code for my view: Here is the code for my controller: public class GetStudentsController : Controlle ...

Enhancing dynamic text boxes with jQuery by incorporating additional information

I've recently developed an interactive app that dynamically creates tables based on user input. The app includes a feature where you can specify the number of tables to generate and track the total count of tables added. Currently, I'm exploring ...

Employ splinter for updating the content of an HTML body

After examining the page source, I discovered that the forum content is contained within an unnamed iframe structured like this: <iframe style="height: 360px;"> <html> <body> Forum discussions are displayed here. ...

Quickly redesigning the appearance of file input using javascript and jquery. Seeking assistance to correct css issues on jsfiddle

Hey there, I've been working on styling the input[type="file"] element and could use some assistance. Like the saying goes, "One JSfiddle is worth 1000 words," so here's the link to my example: --- For more details, click here: http://jsfiddle.n ...

The process of extracting data from a form and storing it as global variables

Consider the following example: This is our HTML form <form action="test1" method="GET" name="frm"> First name: <input type="text" name="fname"><br> Last name: <input type="text" name="lname"><br> <i ...