A chromatic aberration is an optical effect caused by one or more color channels being displaced. Although it is an optical failure and should be avoided for displaying or image capturing devices, chromatic aberration can be used to make graphics be more realistic in some other applications like 3D games.
The following codes is an example of implementing the effect using ImageData API of HTML5 canvas. By fetching and manipulating pixel data of the image, the chromatic aberration effect is easy to achieve.
<html>
<body>
<canvas id="canvas"></canvas>
<script type="text/javascript">
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var image = new Image();
var width, height;
image.src = "1.jpg";
image.onload = function(){
width = image.naturalWidth;
height = image.naturalHeight;
canvas.width = width;
canvas.height = height;
ctx.drawImage(image, 0, 0);
chromaticAberration(ctx, 5, 0);
}
function chromaticAberration(ctx, intensity, phase){
/* Use canvas to draw the original image, and load pixel data by calling getImageData
The ImageData.data is an one-dimentional Uint8Array with all the color elements flattened. The array contains data in the sequence of [r,g,b,a,r,g,b,a...]
Because of the cross-origin issue, remember to run the demo in a localhost server or the getImageData call will throw error
*/
var imageData = ctx.getImageData(0, 0, width, height);
var data = imageData.data;
for (var i = phase % 4; i < data.length; i += 4) {
// Setting the start of the loop to a different integer will change the aberration color, but a start integer of 4n-1 will not work
data[i] = data[i + 4 * intensity];
}
ctx.putImageData(imageData, 0, 0);
}
</script>
</body>
</html>
FYI the images do not load anymore. I turned this gist into a GitHub Pages static site:
https://tomashubelbauer.github.io/canvas-chromatic-aberration/
The backing repository is here:
https://github.com/TomasHubelbauer/canvas-chromatic-abberation
Hope you don't mind! Thanks for putting this gist up.