Rendering a ImageBitMap/Image on an OffScreenCanvas using a web-worker

In my vue.js application, I have implemented vue-workers/web-workers to handle image processing tasks such as scaling and cropping in the background after a user uploads images.

Due to the lack of support for Canvas and Image Object in web workers, I opted to use ImageBitmaps and OffscreenCanvas. I am able to create an ImageBitmap from an image file using the CreateImageBitmap() method which returns a promise that resolves to an ImageBitmap. I have successfully confirmed the creation of the ImageBitmap by printing it to the console.

Click here to view the ImageBitmap created and the error thrown.

var loadingImage = new Image();
loadingImage.onload = () => {

    console.log(createImageBitmap(loadingImage)); // ImageBitmap successfully logged to console
    const canvas = new OffscreenCanvas(100, 100);
    const ctx = canvas.getContext('2d');

    Promise.all([
        createImageBitmaps(loadingImage);
    ]).then(function(result){
        console.log("Promise resolved");
        console.log(result);
        ctx.drawImage(result, 0, 0, 200, 200); // Error occurs at this line
    })  

    // Other code goes here .... 

};
loadingImage.src = base64Src; 

Question: I am facing difficulty when passing the ImageBitmap to the OffscreenCanvas draw() method as it throws an error "failed to execute drawImage on OffscreenCanvasRenderer...". The exact error can be seen in the console after the ImageBitmap is printed in the picture below.

Has anyone been able to successfully draw an image to an OffscreenCanvas within a vue-worker/web-worker setup? Any examples of working code would be greatly appreciated!

Furthermore, based on my research, it seems that createImageBitmap() is only supported in Chrome. Is there an alternative way, other than using ImageBitmap, to draw on OffscreenCanvas that works on both Chrome and Safari?

Answer №1

Did you explore the benefits of leveraging ImageBitmapRenderingContext for your project?

canvas.getContext('bitmaprenderer').transferFromImageBitmap(bitmap);

Answer №2

The example demonstrates that the result type is an array due to the use of Promise.all, which is not supported as an image source. The issue can be resolved by eliminating Promise.all and directly utilizing the resolved result.

var loadingImage = new Image();
loadingImage.onload = () => {

    console.log(createImageBitmap(loadingImage)); // ImageBitmap can be viewed in the console
    const canvas = new OffscreenCanvas(100,100);
    const ctx = canvas.getContext('2d');
    
    createImageBitmap(loadingImage).then(function(result){
        console.log("printing promise resolved");
        console.log(result);
        ctx.drawImage(result,0,0,200,200);  /// <-- error occurs here
    })  

    // additional code goes here .... 

};
loadingImage.src = "https://i.sstatic.net/ioGgw.png"; 

This outputs without any errors (in Chrome):

[object Promise] { ... }
"printing promise resolved"
[object ImageBitmap] {
  close: function close() { [native code] },
  height: 402,
  width: 812
}

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

Using Laravel with Vue and <router-link> does not update the content as expected

For my project, I am using Laravel with Vue. On the main page, I have listed all articles and when a user clicks on a specific article, a new page opens displaying that article with other prominent articles shown on the side like this: .https://i.stack.img ...

Tips on avoiding blurring when making an autocomplete selection

I am currently working on a project to develop an asset tracker that showcases assets in a table format. One of the features I am implementing is the ability for users to check out assets and have an input field populated with the name of the person author ...

The issue code R10, indicating a boot timeout, has arisen as the web process failed to connect to $PORT within 60 seconds of initiating on Heroku platform

After deploying my Node.js WebApp to Heroku, I encountered the following error: 2021-06-01T09:19:42.615419+00:00 heroku[web.1]: State changed from crashed to starting 2021-06-01T09:19:47.259832+00:00 heroku[web.1]: Starting process with command `node app.j ...

Display an "add to cart" button and a discount image when hovering over

Currently, I am in the process of developing an Online Shopping website using PHP. To enhance the design of my website, I have implemented bootstrap. One specific query I have is how to display an 'add to cart' button and a discount image when a ...

Exploring the functionality of window.matchmedia in React while incorporating Typescript

Recently, I have been working on implementing a dark mode toggle switch in React Typescript. In the past, I successfully built one using plain JavaScript along with useState and window.matchmedia('(prefers-color-scheme dark)').matches. However, w ...

Map on leaflet not showing up

I followed the tutorial at http://leafletjs.com/examples/quick-start/ as instructed. After downloading the css and js files to my local directory, I expected to see a map but all I get is a gray background. Can anyone advise me on what might be missing? T ...

Issue with Vue JS: e.preventDefault not functioning correctly when using Axios

I am facing an issue in my Laravel project where I have implemented a method in the Vue instance to validate resource availability upon form submission. The validation is done through an AJAX call using axios, and if any resources are unavailable, I receiv ...

Unable to retrieve custom CSS and JS files hosted on the server

Encountering Server Issue My server is returning a 404 NOT FOUND error when trying to access my static files: css and js. In IntelliJ IDEA, the path appears correct as shown in the image https://i.stack.imgur.com/nTFv9.png. However, upon accessing the pa ...

What is the best way to vertically flip a background image that is repeating along the y axis in CSS?

I am in the process of developing a mobile web app and I need assistance with flipping the background image when it repeats along the y-axis. Can someone guide me on how to achieve this using CSS or JavaScript? https://i.stack.imgur.com/b107V.jpg var el ...

Tips for showcasing varied information on Morris Chart

I am working with a Morris chart that is populated with a collection of data, each item containing 6 different data values. My goal is to switch between displaying two different sets of data. For example, I want to show the 'Target' data always ...

The static folder in Express server is failing to serve files

I have an application with certain static files that I want to send to the client, however the server is not sending them. app.use(express.static(__dirname, '/public')); I need help fixing this particular code snippet. ...

The modules exporting lack the necessary context for this

I'm not entirely happy with how the question is phrased. Feel free to suggest any improvements. Also, please understand that my frustration might be due to a mix of ignorance and annoyance which could result in inaccurate assessments of the issue. I a ...

Troubleshooting a React JS and material-ui issue

Having an issue with material-ui integration in reactjs. Attempting to render a FlatButton, but encountering the error message: TypeError: _context$muiTheme is undefined As a newcomer to reactjs, I'm unsure of where the problem lies. Below is my code ...

Issue with AnimeJS Motion Path causing element to deviate from desired SVG path

I'm attempting to use an SVG element and the AnimeJS library to make the orange marker follow the course of this RC car race track. https://i.stack.imgur.com/8FKHC.png Despite my efforts, I am encountering strange and undesirable outcomes. At times ...

Retrieve a JSON array using an HTTP Get request in JavaScript (with jQuery)

I’ve been experimenting with various code snippets in an attempt to reach my objective, but so far I haven’t found a solution. Objective: My goal is to retrieve a JSON array of objects from a specific web URL using the GET method. This task needs to b ...

Issue with page scrolling while utilizing the Wow.js jQuery plugin

While using the Wow.js plugin for scroll animations, I encountered an issue on mobile phones. When reaching the Pricings section, scrolling becomes impossible for some reason. I am utilizing Bootstrap 3 in this project. Despite attempting to modify the an ...

Addressing memory leaks in React server-side rendering and Node.js with setInterval

Currently in my all-encompassing react application, there's a react element that has setInterval within componentWillMount and clearInterval inside componentWillUnmount. Luckily, componentWillUnmount is not invoked on the server. componentWillMount( ...

Creating audio streams using react-player

I am currently working on integrating the react-player component from CookPete into my website. However, I am facing a challenge in setting up multiple audio streams. Additionally, I want to include both DASH and HLS video streams but adding them as an arr ...

How can I retrieve one distinct document for each group based on a shared property value in MongoDB?

I have a database collection set up in MongoDB with a schema like this: var personSchema = new mongoose.Schema({ _id: ObjectId, name: String, // ... alias: String }; (I am using mongoose, but the details are not important). Because I retrieve pe ...

What's the process for setting a value in selectize.js using Angular programmatically?

Currently, I am implementing the AngularJS directive to utilize selectize.js from this source: https://github.com/kbanman/selectize-ng In my scenario, I have two dropdowns and my goal is to dynamically populate one of them called selectizeVat based on the ...