Last active
May 13, 2019 02:06
-
-
Save mandaputtra/09c45451125711228434c6e3a5d761fc to your computer and use it in GitHub Desktop.
Canvas invert color in image
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<meta http-equiv="X-UA-Compatible" content="ie=edge"> | |
<link rel="stylesheet" href="./css/style.css"> | |
<title>A Gamma Image Editor</title> | |
</head> | |
<body> | |
<h1>Simple Image Gamma Example</h1> | |
<div class="image-container"> | |
<img class="pure-image" src="./assets/img/img.jpg" alt="just an image" srcset="./assets/img/img.jpg"> | |
<canvas class="filter-image" width="500" height="300"> | |
</div> | |
<button id="btn-invert">Click</button> | |
<script src="./src/index.js"></script> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const canvas = document.getElementsByClassName('filter-image')[0] | |
const img = document.getElementsByClassName('pure-image')[0] | |
const invertButton = document.getElementById('btn-invert') | |
const ctx = canvas.getContext('2d') | |
// load image | |
let base_image = new Image() | |
base_image.src = img.src | |
base_image.onload = function() { | |
ctx.clearRect(0, 0, canvas.width, canvas.height) | |
ctx.imageSmoothingEnabled = false | |
ctx.drawImage(base_image, 0, 0, canvas.width, canvas.height) | |
} | |
function invertColors(data) { | |
for (var i = 0; i < data.length; i+= 4) { | |
data[i] = data[i] ^ 210; // Red | |
data[i+1] = data[i+1] ^ 100; // Green | |
data[i+2] = data[i+2] ^ 122; // Blue | |
data[i+3] = data[i+3] ^ 122; // Alpha | |
} | |
} | |
// inverting color | |
function invert() { | |
// get image data | |
const pixels = ctx.getImageData(0, 0, canvas.width, canvas.height) | |
invertColors(pixels.data) | |
ctx.putImageData(pixels, 0, 0) | |
} | |
invertButton.addEventListener('click', invert) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment