Skip to content

Instantly share code, notes, and snippets.

@mandaputtra

mandaputtra/index.html

Last active May 13, 2019
Embed
What would you like to do?
Canvas invert color in image
<!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>
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