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

Guide to quickly redirecting all 404 links to the homepage on a simple HTML website

Is there a way to automatically redirect clients to the homepage if they click on a broken link in a basic HTML website, instead of displaying a custom 404 page? UPDATE: My website consists of only 5 plain HTML pages hosted on GoDaddy. There is no server- ...

I encountered an issue in VueJS where it cannot find the property 'fn' of undefined

I am currently working on a project using VueJS and I have encountered a problem. My goal is to integrate owl.carousel, so I proceeded by installing it through the following command: npm install --save owl.carousel After installation, I imported it into ...

Words of wisdom shared on social media

How can I share text from my HTML page on Twitter? This is the code snippet from my HTML page - function change() { quotes = ["Naam toh suna hi hoga", "Mogambo Khush Hua", "Kitne aadmi the?"]; auth = ["Raj", "Mogambo", "Gabbar"]; min = 0; max = ...

Ways to resolve Error: Project needs yarn, but it is not currently installed

Just finished setting up my new project using the following commands: npm install --global yarn vue create elecprog yarn serve (-> encountered an error) Running everything through VS Code terminal. PS D:\elcp\elecprog> yarn serve yarn run ...

What steps should I take to develop an Outlook add-in that displays read receipts for action items in sent emails?

Currently, I am in the process of developing an add-in that will enable me to track email activity using a tool called lead-boxer (). With this add-in, I am able to retrieve detailed information about users who have opened my emails by sending them with an ...

Can a Vue application be made type-safe without the need for transpilation?

Is it possible for Vue to be type-safe when used without transpilation (without a build step) as well? Can TypeScript or Flow be used to ensure type safety? ...

Generate dynamic v-expansion panels using data from the API

I am currently experiencing an issue with the child component mobReports.vue, which contains v-expansion-panels inside it, but they are not displaying... <template> <v-expansion-panels> <v-expansion-panel v-for="(index, titl ...

What methods can I employ to utilize preg_match with jQuery?

Is it possible to validate a phone number in jQuery using preg_match? I have tried the following code without success: if (!preg_match("/^[0-9]{3}-|\s[0-9]{3}-|\s[0-9]{4}$/", phone.val() )) { phone.addClass("needsfille ...

Exploring the Ins and Outs of Transition Testing in D3 v4

Previously, in older versions of D3, you were able to create unit tests that checked the state of a D3 component after all transitions had finished by flushing the timer with d3.timer.flush(). However, in D3 version 4, this has changed to d3.timerFlush(), ...

Javascript: Dynamically Altering Images and Text

One feature on my website is a translation script. However, I'm struggling to activate it and update the image and text based on the selected language. This is the code snippet I am currently using: <div class="btn-group"> <button type ...

Tips for implementing a selection event in an auto complete dropdown menu:

I am struggling with detecting the selection in this Combobox. For example, if I choose "Massachusetts", I want to be able to access that information. @change call API + populated list - Done ✅ @select doSomething() - Not Done ❌ I have a hard time d ...

After executing the controller function in AngularJS, the loading icon transitions into a status icon

Is it possible to dynamically change an icon in my view based on the status of a controller function? I want the icon to initially display as a spinning wheel to indicate loading and activity while the function is executing. https://i.stack.imgur.com/I ...

Add data to a size guide

My coding project involved creating a sizing chart using HTML, CSS, and JavaScript. The chart allows users to select their preferred units of measurement (metric or imperial). I used JavaScript to dynamically update the values in the chart based on the sel ...

The CORS middleware seems to be ineffective when used in the context of Node.js

I have set up my REST API on a Raspberry Pi server and connected it to the public using localtunnel. I am trying to access this API from a localhost Node.js application. The Node application is running on Express and includes some static JS files. However, ...

I am facing an issue with the clearTimeout function in my JavaScript code. Can anyone help

I am encountering some issues with the clearTimeout() function. The setTimeout() function is working as expected, but I want it to stop running when I close my notification. I'm not sure what is causing the problem in my function. After closing the ...

ReactJS: What is the best way to rearrange elements within an array stored in an object's property?

I am attempting to swap the positions of two elements within an array, which is nested inside an object as a property. However, when I click on the second "^" button in my CodeSandbox example below, I encounter the error message TypeError: arr.container.ma ...

Tips on creating an inline editable cell in a Tree View

I've been working on a category tree that includes expand and collapse buttons. You can see what I have so far here: Category Tree Now, I'm looking to make each item inline editable. Can someone guide me on how to achieve this? If you want to t ...

When using React, appending a React Link tag to an existing list item may result in the addition of two objects instead of the desired

Trying to create a loop that checks if an object's date matches with a date on a calendar. If it does, I want to add a React Link tag to the respective li element. The loop logic works well, but the issue is when appending the Link tag using createTex ...

Creating an entity using various asynchronous sources in node.js/express.js

Struggling to find a solution to my problem online and hoping someone here can help. My express route is making multiple API requests for different JSON objects, but I'm having trouble building a single JSON response for the client side view. All my a ...

What is the best way to integrate a loop in JavaScript to retrieve values?

<script> var data={ Data: { name: 'aaaa', number: '0003' }, values: { val: '-20.00', rate: '22047' }, user: [ '6|1|5', '10|1|15' ] }; ...