Created
September 14, 2012 18:09
-
-
Save vivekrk/3723624 to your computer and use it in GitHub Desktop.
greyscale conversion in canvas
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
console.log('I am here'); | |
var ctx = null; | |
//Converts the bitmap array to greyscale and returns the modified array | |
function applyGreyScaleEffect(ctx) { | |
console.log('applyGreyScaleEffect'); | |
var start = new Date().getTime(); | |
var recall = {}; | |
var imageData = ctx.getImageData(0,0,2048,1536); | |
for(var y = 0; y < imageData.height; y++){ | |
for(var x = 0; x < imageData.width; x++){ | |
var i = (y * 4) * imageData.width + x * 4; | |
var color = imageData.data[i] + imageData.data[i + 1] + imageData.data[i + 2]; | |
//console.log('color: ' + imageData.data[i] + ":" + imageData.data[i + 1] + ":" + imageData.data[i + 2]); | |
//Check if you have already encounted this color. | |
var avg = recall[color]; | |
if(avg) { | |
imageData.data[i] = avg; | |
imageData.data[i + 1] = avg; | |
imageData.data[i + 2] = avg; | |
} else { | |
avg = color / 3; | |
recall[color] = avg; | |
imageData.data[i] = avg; | |
imageData.data[i + 1] = avg; | |
imageData.data[i + 2] = avg; | |
} | |
} | |
} | |
ctx.putImageData(imageData, 0, 0); | |
var end = new Date().getTime(); | |
var time = end - start; | |
console.log('The function took: ' + time); | |
} | |
function handleClick() { | |
console.log('Click event'); | |
applyGreyScaleEffect(ctx); | |
} | |
/*function timeFunction() { | |
var start = new Date().getTime(); | |
var end = new Date().getTime(); | |
var time = end - start; | |
return time; | |
}*/ | |
document.addEventListener('DOMContentLoaded', function() { | |
console.log('DOMContentLoaded'); | |
ctx = document.getElementById('myCanvas').getContext('2d'); | |
var img = new Image(); | |
img.src = "https://dl.dropbox.com/u/8690649/image.jpg"; | |
img.onload = function () { | |
ctx.drawImage(img,0,0,2048,1536); | |
} | |
document.getElementById('grey').onclick = handleClick; | |
}, false); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment