Optical illusion - 18 lines of pure JavaScript



Here's a cool optical illusion - you should see little white dots in the intersections of the gray lines where you focus your vision, but they seem to disappear from your peripheral vision. Please note that this is a static image - it does not change, but your brain thinks it does.

The code to create this effect is very simple:

[Lines 4-6]: set up the HTML5 Canvas
[7-9]: prepare to draw the gray lines
[10-12]: draw the lines going South-West
[13-16]: draw the lines going South-East
[18-24]: draw the white circles. In every iteration of the y loop we draw two circles - the second one is to shifted down and right, so that we cover each intersection.

<html>
<body style='background-color:black'>
<canvas id="myCanvaswidth="800height="340"></canvas>
<script>
let canvas = document.getElementById('myCanvas');
let context = canvas.getContext('2d');
context.lineWidth = 5;
context.strokeStyle = 'gray'
context.beginPath();
for(let x=0;x<28;x++){
        context.moveTo(x*40-304,0);
        context.lineTo(x*40+20,340);
        context.moveTo(x*40,0);
        context.lineTo(x*40-324,340);
        }
context.stroke();
 
context.fillStyle = 'white';
for(let x=0;x<20;x++)
        for(let y=0;y<9;y++){
                context.beginPath();
                context.arc(8+x*40y*42-9302 * Math.PI);
                context.arc(28+x*40y*42-29302 * Math.PI);
                context.fill();                        
                }
</script>
</body>
</html>


Changing the size and reducing the number of circles lead to interesting effects. Enjoy fooling your brain!





Check out these programming tutorials:

JavaScript:

Oldschool fire effect (20 lines)

Animated fractal (32 lines)

8-bit sine scroll (30 lines)

Physics engine for beginners

Starfield (21 lines)

Yin Yang with a twist (4 circles and 20 lines)

Tutorial - interactive, animated sprites

Your first program in JavaScript: you need 5 minutes and a notepad


Fractals in Excel

Python in Blender 3d:

Domino effect (10 lines)


Wrecking ball effect (14 lines)

3d fractal in Blender Python