6 votes

How many dots can you see? Optical illusion in 18 lines of pure JavaScript - easy tutorial

2 comments

  1. Emerald_Knight
    (edited )
    Link
    Magic numbers. Magic numbers everywhere. Recommended would be to store certain numbers into variables to provide missing yet essential context, e.g. storing 40 in the variable line_spacing. The...

    Magic numbers. Magic numbers everywhere. Recommended would be to store certain numbers into variables to provide missing yet essential context, e.g. storing 40 in the variable line_spacing. The author states "Changing the size and reducing the number of circles lead to interesting effects. Enjoy fooling your brain!", but the code in its current form doesn't facilitate this sort of experimentation without a great deal of effort.

    Don't get me wrong, it's pretty neat to see something like this. I just feel the urge to do a refactor :)

    6 votes
  2. teaearlgraycold
    (edited )
    Link
    Here's a similar one in GLSL: https://www.shadertoy.com/view/tslSRS const float PI = 3.14159265359; const float n_stripes = 25.0; // 0.. const float stripe_width = 0.2; // 0..1 mat2 rotate2d(float...

    Here's a similar one in GLSL:

    https://www.shadertoy.com/view/tslSRS

    const float PI = 3.14159265359;
    const float n_stripes = 25.0; // 0..
    const float stripe_width = 0.2; // 0..1
    
    mat2 rotate2d(float angle){
        return mat2(
            cos(angle), -sin(angle),
            sin(angle),  cos(angle)
        );
    }
    
    void mainImage(out vec4 fragColor, in vec2 fragCoord)
    {
        // Convert coord from pixels to units of screen height - also compensates for aspect ratio.
        // Then rotate by 45 degrees.
        vec2 uv = (fragCoord / vec2(iResolution.y)) * rotate2d(PI / 4.0);
    
        // These names are a bit dishonest when the image is rotated.
        // vert and horiz could be computed in a single expression, but for code that will be toyed with
        // keeping them separate improves the hackability.
        float vert = ((mod(uv.x, 1.0 / n_stripes) * n_stripes) < stripe_width) ? 0.5 : 0.0;
        float horiz = ((mod(uv.y, 1.0 / n_stripes) * n_stripes) < stripe_width) ? 0.5 : 0.0;
    
        fragColor = vec4(vec3(vert + horiz), 1.0);
    }
    

    Edit: Added a few comments to the code