2

I'd like to compare (a limited number of) color values retrieved from an HTML5 canvas. So I retrieve and store what I'm interested in by ctx.getImageData(x, y, 1, 1).data;

I then tried to use the Array.prototype.compare from: How to compare arrays in JavaScript? by:

// add the same compare method to Uint8ClampedArray
Uint8ClampedArray.prototype.compare=Array.prototype.compare;

That works fine on recent FireFox and Chrome but I soon found that not all browsers return an object of type Uint8ClampedArray. IE seems to use an Object of CanvasPixelArray and Safari seems to use a simple 4-value array

Do I have to deal with those differences myself or is there a reliable generelized method (plain JS or jQuery) to compare two such values retieved by ctx.getImageData() that works on all browsers?

Community
  • 1
  • 1
C.O.
  • 2,281
  • 6
  • 28
  • 51

1 Answers1

1

You can (probably?) use the Array compare method like this:

var comparisonResult = [].compare.call(yourPixels, colors);

That code finds the "compare" method from an array instance and invokes it with your pixel array as the this value and the other array (your colors) as the first parameter.

This would be the same thing:

var comparisonResult = Array.prototype.compare.call(yourPixels, colors);

but it's more typing and I'm lazy. Anyway, as long as the pixels "look like" an array (they have a "length" property and [] indexing works) that should work for you.

edit — I just looked at the question you linked. If you just need a "compare" function for this purpose, there's no need to add it to the Array prototype, since you're not making use of it by that means anyway. Just write a compare function that takes two arguments.

Pointy
  • 405,095
  • 59
  • 585
  • 614