JavaScript Example: Optical Illusion

This example is based on the article by Edward H. Adelson at M.I.T about optical illusions. The use of JavaScript can better advocate for the evidence of illusion. On the picture below, the article claims that the squares marked A and B are the same color, which appears obviously false. But if we keep pressed the mouse on the image, it brings up two gray strips and by comparing the colors of stripes with those of squares A and B, it becomes obvious that the color is the same!

Click on the image

Explaining the illusion ...

The illusion comes from that the brain discerns the shadow from the cylinder and corrects the color of the square B by subtracting the darkening due to the shadow.

How is build the JavaScript code

This demonstration is here to serve as an illustration of the management of events in JS.

First, the two images, with and without gray bands are pre-loaded with the following code:

var illusion = new Image(); 
var proof = new Image(); 
illusion.src = "shadow-illusion.jpg";        
proof.src = "shadow-proof.jpg";

By creating objects Image and assigning them a file, it causes the loading in memory of this file.
To rotate the images, two event managers are assigned to the img tag:

Onmousedown: an event is triggered when the mouse is pressed on the image.

Onmouseup: an event is triggered when the mouse is released over the image.

This is used in the following code:

<img src="shadow-illusion.jpg" width="540" height="420"
   onmousedown="press(this)"
   onmouseup="depress(this)">

It remains to add the two functions:

function press(element)
{
  element.setAttribute("src", proof.src);	
}

function depress(element)
{
  element.setAttribute("src", illusion.src);	
}

The argument "element" of the functions is given by the keyword this at call, and that represents the container tag, thus img. To change the image, the attribute "src" of the tag is assigned the name of the new file, that is taken from the attribute "src" of Image objects that had been previously created!

© 2007-2014 Xul.fr