sjudǝʊ
sjudǝʊ

Reputation: 1565

canvas data to web worker

I'm trying to do some processing with webworker on image data from canvas. Solution, that I have right know, works quite ok, but there are still some visible lags when I do the processing (because besides processing I have to draw video from webcam to canvas and it starts to lag).

So I tried to use webworker and I did everything asynchronously. The only problem is that when I use JSON.stringify, it takes longer than actual processing.

My question: is there any other way, how to pass lot of data via worker.postMessage quickly? Is there some kind of workaround that I don't know about?

Small subquestion: what for are webworkers? I find workers really useless, passing just strings.

EDIT:

possible duplicate: Pass large amounts of data between web worker and main thread

Upvotes: 4

Views: 1959

Answers (1)

beatgammit
beatgammit

Reputation: 20225

Everything is copied to a webworker, so unless your computation is very intensive, I doubt you'll see much gain there.

WebWorkers are meant for long-running, computationally intensive algorithms. The obvious use cases are:

  • AI in web games
  • Raytracers
  • Compression/decompression on large data sets
  • AJAX requests that need a lot of processing before it's displayed
  • Other complex algorithms

Since data is copied both ways, you have to be careful about what you're doing. WebWorkers don't have access to the DOM, so they're likely useless for what you're trying to do. I don't know what your app does, but it sounds like it isn't very intense.

There are also Sharedworkers, which can be shared by multiple tabs/windows, which is a really nice way to pass data between tabs.

Edit:

Also look into the structured clone algorithm. It seems to be more efficient that JSON for many things, and can even duplicate ImageData (so it doesn't just support strings anymore).

For browsers that don't support the clone algorithm, I would urge you to consider base64. It's decent at storing binary data, and I think it's faster than JSON.stringify. You may have to write some code to handle it though.

Upvotes: 3

Related Questions