Modifying canvas image data

by John Schulz

JavaScript

(function() {
    var x, d = 'Please use a browser that supports canvas.', join = [].join,
        splice = [].splice, c = document.createElement('canvas');
    
    if (typeof c.getContext != 'undefined') {
        c.width = c.height = 1;
        x = c.getContext('2d').getImageData(0, 0, 1, 1);
        d = x.data;
        
        try {
            splice.call(d, 2, 2, 1, 1);
            alert('spliced: expected [0,0,1,1]; got [' + join.call(d) + ']');
        } catch (e) {
            alert(e);
        }
        
        try {
            x.data = [1, 1, 1, 1];
            alert('set with real array: expected [1,1,1,1]; got [' + join.call(x.data) + ']');
        } catch (e) {
            alert(e);
        }
    }
    else {
        alert(d);
    }
})();