开发者

Javascript Image manipulation Invert color

I am trying to play with an image inside a webpage using javascript and it is being a pain. I have no coding platform atm except my browser. It should invert the color I think but i'm not sure what is screwing up. What is wrong with my script?

<img src="C:\Documents and Settings\_username_\Desktop\rabbit.jpg" name="myimage" id="myimage">
<input type="button" value="Click Here" onClick="doSomething();">
<SCRIPT language=JavaScript>

  function doSomething(){

    var imgd = myimage.getImageData(x, y, width, height); 
    var pix 开发者_Go百科= 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
       // i+3 is alpha (the fourth element) 
    }  

    myimage.putImageData(imgd, x, y); 
  }
</SCRIPT>


If you are using MS Internet Explorer, the following code should work for you

<img src="xyz.jpg" onMouseover="this.style.filter='progid:DXImageTransform.Microsoft.BasicImage(invert=1)'" onMouseout="this.style.filter=''" />

Post IE 8 it the "filter" should be replaced by "-ms-filter"

Also a smarter way is mentioned at the sohtanaka site, which uses jquery and css to accomplish the required effect http://www.sohtanaka.com/web-design/greyscale-hover-effect-w-css-jquery/

Hope this helps you :-)


The xolor library has an inverse function:

xolor("rgb(100,200,50").inverse().rgb // returns the inverse in rgb format

Its implemented like this, where it already parsed the red, green, and blue values which exist as properties on the xolor object:

this.inverse = function() {
    return xolor({
        r: this.r ^= 0xff,
        g: this.g ^= 0xff,
        b: this.b ^= 0xff
    })
}


That would work on a canvas context, but you're working with an image. Create a canvas and copy the image's data into it and then invert the colors.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜