Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 Canvas: Invert Color of Pixels

I am following the tutorial on WC3 found here: http://www.w3schools.com/tags/canvas_getimagedata.asp

I have my image loaded up and next to this is the canvas which I have a nice boarder and I'm intending to display side-by-side images. I am attempting to invert the color of the pixel as the demonstration but I cannot get the colors to change I don't understand why.

Here is my code pen where I separated the HTML from the JS: http://codepen.io/kKasper/pen/zBXWOZ

document.getElementById("team").onload = function() {
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var img=document.getElementById("team");
    ctx.drawImage(img, 0, 0);
    var imgData = ctx.getImageData(0, 0, c.width, c.height);
    // invert colors
    var i;
    for (i = 0; i < imgData.data.length; i += 4) {
        imgData.data[i] = 255 - imgData.data[i];
        imgData.data[i+1] = 255 - imgData.data[i+1];
        imgData.data[i+2] = 255 - imgData.data[i+2];
        imgData.data[i+3] = 255;
    }
    ctx.putImageData(imgData, 0, 0);
};

It appears that ctx.drawImage(img, 0, 0); is drawing my image inside the canvas. For some reason the function that works on the WC3 tutorial is not working properly on my image because when it draws the image after the function there are no changes.

Can anyone help me solve this please?

like image 868
Kasper_Sky Avatar asked Aug 19 '16 21:08

Kasper_Sky


People also ask

How do I invert colors in pixels?

Open your device's Settings app . Select Accessibility. Under "Color and motion," select Color inversion. Turn on Use color inversion.

How do you invert an image on canvas?

To flip an image in Canva: Select the image. Click “Flip” Select “Flip horizontal” or “Vertical”

How do you invert the colors of an image in HTML?

CSS allows you to invert the color of an HTML element by using the invert() CSS function that you can pass to the filter property. Because the default color of the text is black, the color is inverted into white with filter: invert(100%) syntax.


1 Answers

You can use compositing to invert your image as long as your browser supports blending.

Advantages:

  • This is faster than getImageData
  • The canvas won't object with cross-origin security restrictions

enter image description here

ctx.drawImage(img,0,0);
ctx.globalCompositeOperation='difference';
ctx.fillStyle='white';
ctx.fillRect(0,0,canvas.width,canvas.height);
like image 116
markE Avatar answered Sep 28 '22 09:09

markE