public
Description: prototype.js tidbits
Homepage: http://thinkweb2.com/projects/prototype/
Clone URL: git://github.com/kangax/protolicious.git
protolicious / canvas_assertions.js
100644 63 lines (60 sloc) 2.024 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
(function(){
  /**
* @private
* @method iterateData
* @param {CanvasRenderingContext2D} ctx context to test
* @param {Function} fn Callback, invoked with `currentValue`, `previousValue` and `index`.
* Breaks out of the loop if callback returns `false`.
*/
  function iterateData(ctx, fn) {
    var data = ctx.getImageData(0, 0, ctx.canvas.width, ctx.canvas.height).data;
    for (var i = data.length; i--; ) {
      if (i > 4) {
        if (fn(data[i], data[i - 4], i) === false) break;
      }
    }
  }
  
  /**
* @method assertColor
* @param {CanvasRenderingContext2D} ctx context to test
* @param {String} color color in a hex value
* @return {Boolean | null} `true` if all canvas pixels are of a given color, `null` if wrong color is given
* @example `assertColor(canvas._oContextContainer, 'ff5555');`
*/
  function assertColor(ctx, color) {
    var match, r, g, b;
    if (match = String(color).match(/^#?([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})$/i)) {
      r = parseInt(match[1], 16);
      g = parseInt(match[2], 16);
      b = parseInt(match[3], 16);
    }
    else return null;
    var result = true;
    iterateData(ctx, function(currentValue, prevValue, i) {
      if ((!(i % 4) && (currentValue !== r)) ||
          (!((i-1) % 4) && (currentValue !== g)) ||
          (!((i-2) % 4) && (currentValue !== b))) {
        return (result = false);
      }
    });
    return result;
  }
  
  /**
* @method assertSameColor
* @param {CanvasRenderingContext2D} ctx context to test
* @return {Boolean} `true` if all canvas pixels are of the same color
* @example `assertSameColor(canvas._oContextContainer);`
*/
  function assertSameColor(ctx) {
    var result = true;
    iterateData(ctx, function(currentValue, prevValue, i) {
      if (currentValue !== prevValue) {
        return (result = false);
      }
    });
    return result;
  }
 
  // export as global
  this.assertColor = assertColor;
  this.assertSameColor = assertSameColor;
})();