canvas + chrome + content

I am writing an extension that attaches a div and a canvas to content pages, and in the process of trying to tune it for performance, I ran into bug 339587. I submitted a patch for that bug, but I ran into another problem, which is that my patch causes the ImageData to be wrapped (it becomes a SafeJSObjectWrapper), which means that subsequent putImageData calls are foiled; the object doesn’t look like an object anymore, and especially, the data member doesn’t look like an array, so eventually an exception is thrown. putImageData could be made more robust, but the cost might not be worth it… here’s the obvious workaround. You needn’t actually call createImageData, ever (at least not currently — this might change??); instead, you can build a JS object that looks and works precisely like an ImageData object in your own code. Since you’ll be setting the pixels yourself anyway, I suspect that creating your own image data is actually a tiny bit faster than using createImageData. Here’s what I did:

let imgData = { width: width, height: height };
imgData.data = new Array(width * height * 4); // make sure your array never needs to grow dynamically
//.... initialization loop ....

This probably seems like an obvious workaround, but it might not be obvious to those who haven’t inspected the get/putImageData code.

The Conversation {1 comments}

  1. Boris {Thursday April 9, 2009 @ 5:54 am}

    As I mentioned to Brian yesterday, createImageData()’s filling in the array has the nice property that you can fill you image data in any order without a performance penalty. If you use your own object and don’t pre-initialize the array yourself, then you run into serious performance issues in SpiderMonkey if you fill it in any order but row order (so fill in the first row starting on the left, then the second row, etc), due to the array becoming sparse. In particular, if your data is best filled in a column at a time, that approach will really hurt.

Leave a Comment

  • Comment Policy:Could go here if there's a nagging need Login Instructions: Would go here if there's a desire.