aroberge / reeborg

Enhanced Karel-the-robot clone
http://reeborg.ca/reeborg.html
Other
47 stars 36 forks source link

Given an image for an object, automatically create the corresponding greyscale goal image #262

Closed aroberge closed 8 years ago

aroberge commented 8 years ago

http://www.hongkiat.com/blog/grayscale-image-web/

var imgObj = document.getElementById('js-image');
function gray(imgObj) {
    var canvas = document.createElement('canvas');
    var canvasContext = canvas.getContext('2d');

    var imgW = imgObj.width;
    var imgH = imgObj.height;
    canvas.width = imgW;
    canvas.height = imgH;

    canvasContext.drawImage(imgObj, 0, 0);
    var imgPixels = canvasContext.getImageData(0, 0, imgW, imgH);

    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;
        }
    }
    canvasContext.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);
    return canvas.toDataURL();
}
imgObj.src = gray(imgObj);
aroberge commented 8 years ago

This cannot be guaranteed to work due to https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image: I cannot ensure that the 3rd party CORS server will have the appropriate headers.