Web Analytics
Refraction of light in p5.js – rays and Snell's law

Refraction of light in p5.js – rays and Snell's law

The ninth lesson of the guide Program a physics simulation. There is no motion in time here – the simulation is geometry: from the mouse position we calculate the angle of incidence, and from the law of refraction the direction of the refracted ray. Move the mouse in the upper half of the canvas; with the keys 1, 2, 3 you choose water, glass or diamond, and the key Z swaps the media (the light then goes from a denser into a less dense medium).

Physics: geometrical optics – the law of refraction n₁ · sin α = n₂ · sin β, total internal reflection, the critical angle.

Programming: angles from coordinates (atan2), inverse trigonometric functions (asin), radians and degrees, the mouseMoved event.

You should know: lesson 2 (sine and cosine, radians).

Step 1: the angle from the mouse position

The ray goes from the mouse to the point O on the boundary. We get the angle measured from the normal (the vertical line) with the function atan2(dx, dy), which returns the angle in radians from the two sides of a right triangle. Until the mouse moves, the angle is 40°.

let alpha = radians(40);
if (mouseMovedOnce) {
  alpha = atan2(ox - constrain(mouseX, 0, width), oy - constrain(mouseY, 0, oy - 1));
}

Step 2: the law of refraction

From Snell's law n₁ · sin α = n₂ · sin β we calculate sin β, and the angle itself with the function asin() (arcsine – “the angle whose sine is…”). We draw the ray from the point O, in the direction of the angle β, downwards:

const s = n1 * sin(alpha) / n2;
if (abs(s) <= 1) {
  const beta = asin(s);
  line(ox, oy, ox + R * sin(beta), oy + R * cos(beta));                // refracted ray
}

From air into water at α = 40° the program gives β = 28.9° – the ray bends towards the normal. Into glass 25.4°, and into diamond only 15.4°.

Step 3: total internal reflection

If the light goes from a denser into a less dense medium (key Z), sin β can come out larger than 1 – such an angle does not exist. Then there is no refracted ray: all the light is reflected. That is why the program checks abs(s) <= 1 before asin, and otherwise draws only the reflected ray. The critical angle is the one for which sin β is exactly 1:

sin αc = n₂ / n₁

For water it is 48.8°, for glass 41.8°, and for diamond only 24.4° – that is why a diamond sparkles so much.

Whole program

Copy it into the p5.js editor and delete the line canvas.parent('lesson-canvas');.

// Refraction of light – program from the lesson “Program a physics simulation” (simulacije.svetprogramiranja.com)
let n1 = 1.0;            // refractive index of the upper medium (where the light comes from)
let n2 = 1.33;           // refractive index of the lower medium
let mouseMovedOnce = false;  // until the mouse moves, the angle of incidence is 40°

function setup() {
  const canvas = createCanvas(320, 320);
  canvas.parent('lesson-canvas');
}

function mouseMoved() {
  if (mouseX >= 0 && mouseX <= width && mouseY >= 0 && mouseY < height / 2) {
    mouseMovedOnce = true;
  }
}

function draw() {
  background(248, 250, 252);
  const ox = width / 2;              // the point where the ray hits the boundary
  const oy = height / 2;
  const R = 150;                     // length of a ray in the drawing, pixels

  // lower medium and the normal
  noStroke();
  fill(186, 230, 253);
  rect(0, oy, width, oy);
  stroke(148, 163, 184);
  strokeWeight(1);
  line(ox, 10, ox, height - 10);

  // angle of incidence α (from the normal): from the mouse position or 40°
  let alpha = radians(40);
  if (mouseMovedOnce) {
    alpha = atan2(ox - constrain(mouseX, 0, width), oy - constrain(mouseY, 0, oy - 1));
  }

  // incident ray: from above to the point (ox, oy)
  stroke(234, 179, 8);
  strokeWeight(3);
  line(ox - R * sin(alpha), oy - R * cos(alpha), ox, oy);

  // Snell's law: n1 · sin α = n2 · sin β
  const s = n1 * sin(alpha) / n2;
  let label;
  if (abs(s) <= 1) {
    const beta = asin(s);
    line(ox, oy, ox + R * sin(beta), oy + R * cos(beta));                // refracted ray
    stroke(234, 179, 8, 90);
    strokeWeight(1.5);
    line(ox, oy, ox + R * sin(alpha), oy - R * cos(alpha));              // weak reflected ray
    label = 'β = ' + degrees(beta).toFixed(1) + '°';
  } else {
    line(ox, oy, ox + R * sin(alpha), oy - R * cos(alpha));              // all the light is reflected
    label = 'total internal reflection';
  }

  noStroke();
  fill(11, 19, 36);
  textSize(13);
  text('n1 = ' + n1.toFixed(2) + ',  n2 = ' + n2.toFixed(2) + '   (1, 2, 3, Z)', 10, 20);
  text('α = ' + degrees(alpha).toFixed(1) + '°,  ' + label, 10, 40);
  if (n1 > n2) {
    text('critical angle = ' + degrees(asin(n2 / n1)).toFixed(1) + '°', 10, 60);
  }
}

function keyPressed() {
  if (key === '1') { n2 = 1.33; }                 // water
  if (key === '2') { n2 = 1.5; }                  // glass
  if (key === '3') { n2 = 2.42; }                 // diamond
  if (key === 'z' || key === 'Z') {               // swap the media
    const temp = n1;
    n1 = n2;
    n2 = temp;
  }
}

Tasks for you

  1. Press Z (water → air) and move the mouse. At what angle of incidence does the refracted ray disappear? Compare with the printed critical angle.
    Solution

    The refracted ray disappears at about 48.8° – exactly at the critical angle. Just before that the refracted ray runs almost along the boundary (β close to 90°).

  2. Add an arc marking the angle α (the function arc) and a label “α” next to it.
    Solution

    For example noFill(); arc(ox, oy, 60, 60, -HALF_PI - alpha, -HALF_PI); – angles in arc are measured from the right horizontal, clockwise.

  3. Add a glass plate: after refraction into the glass, at the bottom edge of the plate the ray passes into air again. What do you notice about the direction of the outgoing ray?
    Solution

    At the second boundary the same law applies with the indices swapped (1.5 → 1.0), so the outgoing ray has the same angle as the incident one (40°) – it is parallel to the incident ray, just shifted sideways.

  4. Dispersion: the refractive index of glass for red light is about 1.51, and for violet light about 1.53. Draw both rays in different colours. Which one bends more?
    Solution

    At α = 40° the red ray has β ≈ 25.2°, and the violet one ≈ 24.8° – violet bends more. That is why a prism splits white light into the colours of the rainbow.

Next