I just wrote a little script that resizes uploaded images into canvas thumbnails. While resizing images it slows down the rest of the web page.
I just discovered web workers which I was hoping I could use to alleviate this problem by moving the resizing task into the background.
The MDN article says you can't access the DOM, which is fine, but I was hoping I could still create DOM elements and pass a canvas back.
However, the Image
object doesn't even seem to exist from inside my worker thread. Chrome tells me:
Uncaught ReferenceError: Image is not defined resize_image.js:4
So... is there a way to do this without using those elements? I just want to manipulate the image data and then pass it back to the main thread in a usable form. I don't really care about the DOM elements themselves, but I'm not sure if the JS API gives me any other options?
My current resize method, which requires access to DOM elements:
resizeImage: function(file, width, height, callback) {
var reader = new FileReader();
reader.onload = function (fileLoadEvent) {
var img = new Image();
img.onload = function() {
var srcX = 0, srcY = 0, srcWidth = img.width, srcHeight = img.height, ratio=1;
var srcRatio = img.width/img.height;
var dstRatio = width/height;
if(srcRatio < dstRatio) {
ratio = img.width/width;
srcHeight = height*ratio;
srcY = (img.height-srcHeight)/2;
} else {
ratio = img.height/height;
srcWidth = width*ratio;
srcX = (img.width-srcWidth)/2;
}
var canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext('2d');
ctx.drawImage(this, srcX, srcY, srcWidth, srcHeight, 0, 0, width, height);
callback(canvas);
};
img.src = reader.result;
};
reader.readAsDataURL(file);
},