JSFiddle - React, Tailwind, and code Playground
by jdsans
HTML
<script src="https://raw.github.com/betamax/getImageData/master/jquery.getimagedata.min.js"></script>
<div class="item first">
<a href="http://themify.me"><img src="http://2.s3.envato.com/files/2466291/milkyway.__large_preview.png"></a>
</div>
JavaScript
// Grayscale w canvas method
var image_url = $(".item img").attr("src"); //gets the image Location
var new_attr = grayscale(image_url); //passes image URL to the grayscale function
$("item img").attr({src:new_attr}); //sets the return value from grayscale as new src value of image
function grayscale(src) {
$.getImageData({ // You can get more information about its at http://www.maxnov.com/getimagedata/#usage
url: src,
success: function (image) {
var can = document.createElement('canvas');
var ctx = can.getContext('2d');
can.width = image.width;
can.height = image.height;
ctx.drawImage(image, 0, 0, image.width, image.height);
var imgPixels = ctx.getImageData(0, 0, can.width, can.height);
for (var y = 0; y < imgPixels.height; y++) {
for (var x = 0; x < imgPixels.width; x++) {
var i = (y * 4) * imgPixels.width + x * 4;
var avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3;
imgPixels.data[i] = avg;
imgPixels.data[i + 1] = avg;
imgPixels.data[i + 2] = avg;
}
}
// Write the image data to the canvas
ctx.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);
return can.toDataURL(); // Here is where the real problem starts.The function doesn't return the Grayscale URL to the called function.
// See this page for an example http://jsfiddle.net/jdsans/Fqt2q/
// In http://jsfiddle.net/jdsans/Fqt2q/ I was trying to get result like this http://webdesignerwall.com/demo/html5-grayscale/
},
error: function(xhr, text_status) {
// Handle your error here
}
});
}