0

I'm trying to manipulate the pixels of an image to invert the color and write back to the canvas. But it's not working. Here's the code:

<script type="text/javascript">
<!--
window.addEventListener('load', function () {
  var elem = document.getElementById('myCanvas');
  var context = elem.getContext('2d');
  var img = new Image();

  img.addEventListener('load', function () {
      var x = 0, y = 0;

      context.drawImage(this, x, y);

      var imgd = context.getImageData(x, y, this.width, this.height);
      var pix = imgd.data;

      for (var i = 0, n = pix.length; i < n; i += 4) {
        pix[i  ] = 255 - pix[i  ]; // red
        pix[i+1] = 255 - pix[i+1]; // green
        pix[i+2] = 255 - pix[i+2]; // blue
      }

      context.putImageData(imgd, x, y);
  }, false);

  img.src = 'test.jpg';
}, false);
// -->
</script>

And the 'Test.jpg' is on the same folder as the script. Am I missing anything? It displays the same image without inverting.

Sebastien C.
  • 4,649
  • 1
  • 21
  • 32
user1004912
  • 106
  • 1
  • 7

2 Answers2

1

the answer to your question is right here

Tested on chrome, and it seem to be the file:// scheme that breaks it. When I moved the script to my local server (http://) instead of running the file (file://), it worked!

Proof: Normally white backgrounded image

Community
  • 1
  • 1
f2lollpll
  • 997
  • 6
  • 15
0

I just tried that example and it seemed to work for me fine. I got a negative/inverted image rendered. Using Firefox 10.0.2

RoryH
  • 90
  • 5
  • I'm using chrome. It doesn't work for me in the Firefox either. – user1004912 Feb 22 '12 at 17:17
  • I updated firefox to 10.0.2 and I see the inverted image too. I'm confused now. All this time I was under impression that chrome supports HTML5 canvas. IE9 does. Does Safari supports HTML5 canvas? – user1004912 Feb 22 '12 at 18:35
  • so the conclusion is that FireFox doesn't keep the standards? or Chrome is to secure? – f2lollpll Feb 23 '12 at 08:02