Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <div id="controls">
  <div>
    <input type="range" id="rays" min="2" max="50" step="1">
    <label for="rays">Num rays</label>
    <input type="checkbox" id="en1" checked="true">
    <label for="en1">Lens 1</label>
    <input type="checkbox" id="en2" checked="true">
    <label for="en2">Lens 2</label>
    <input type="checkbox" id="en3" checked="true">
    <label for="en3">Lens 3</label>
  </div>
  <div>
    <input type="range" id="bnd1" min="100" max="2000" step="10">
    <label for="bnd1">Boundary 1</label>
    <input type="range" id="dist1" min="1" max="500" step="1">
    <label for="dist1">Dist before lens 1</label>
  </div>
  <div>
    <input type="range" id="bnd2" min="100" max="2000" step="10">
    <label for="bnd2">Boundary 2</label>
    <input type="range" id="thk1" min="2" max="50" step="1">
    <label for="thk1">Thickness 1</label>
  </div>
  <div>
    <input type="range" id="bnd3" min="100" max="2000" step="10">
    <label for="bnd3">Boundary 3</label>
          <input type="range" id="dist2" min="1" max="500" step="1">
    <label for="dist2">Dist before lens 2</label>
  </div>
  <div>
    <input type="range" id="bnd4" min="100" max="2000" step="10">
    <label for="bnd4">Boundary 4</label>
      <input type="range" id="thk2" min="2" max="50" step="1">
    <label for="thk2">Thickness 2</label>
  </div>
  <div>
    <input type="range" id="bnd5" min="100" max="2000" step="10">
    <label for="bnd5">Boundary 5</label>
          <input type="range" id="dist3" min="1" max="500" step="1">
    <label for="dist3">Dist before lens 3</label>
  </div>
  <div>
    <input type="range" id="bnd6" min="100" max="2000" step="10">
    <label for="bnd6">Boundary 6</label>
      <input type="range" id="thk3" min="2" max="50" step="1">
    <label for="thk3">Thickness 3</label>
  </div>
  <div>
    <input type="range" id="sensor" min="100" max="1000" step="1">
    <label for="sensor">Sensor location</label>
  </div>
</div>
<div>
  <canvas id="canvas" width="1000" height="300"></canvas>
</div>
<div>
  <p>Measurements</p>
  <p>Effective focal length: <span id="focal_l">...</span></p>
  <p>Highlight height (must be zero for EFL to be valid): <span id="hlht">...</span></p>
  <p>Back focal distance: <span id="bfd">...</span></p>
</div>
              
            
!

CSS

              
                div {
  /* border: solid 1px; */
}
              
            
!

JS

              
                const draw_axis = (ctx) => {
  ctx.beginPath();
  ctx.strokeStyle = "black"
  ctx.moveTo(0, 150);
  ctx.lineTo(1000, 150);
  ctx.closePath();
  ctx.stroke();
}

const draw_aligned_vertical_boundary = (ctx, pos) => {
  ctx.beginPath();
  ctx.strokeStyle = "black"
  ctx.moveTo(pos, 0);
  ctx.lineTo(pos, 300);
  ctx.closePath();
  ctx.stroke();
}

const draw_aligned_circular_boundary = (ctx, origin, center) => {
  const x = origin + center;
  const y = 150;
  const radius = Math.abs(center);
  ctx.beginPath();
  ctx.strokeStyle = "black"
  ctx.arc(x, y, radius, Math.PI/2, Math.PI*3/2, center < 0 );
  ctx.stroke();
}

const draw_raylike = (ctx, start, direction, color, scale=50) => {
  ctx.beginPath();
  ctx.fillStyle = color;
  ctx.arc(start.x, 150-start.y, 3, 0, 2 * Math.PI);
  ctx.fill();
  
  const rx = direction.x;
  const ry = -direction.y;
  const mag = Math.sqrt((rx*rx)+(ry*ry))
  const nx = rx / mag * scale;
  const ny = ry / mag * scale;
  ctx.beginPath();
  ctx.strokeStyle = color;
  ctx.moveTo(start.x, 150-start.y);
  ctx.lineTo(start.x + nx, 150-start.y + ny);
  ctx.stroke();
}

const draw_ray = (ctx, start, direction) => draw_raylike(ctx, start, direction, 'red', 25)
const draw_normal = (ctx, start, direction) => draw_raylike(ctx, start, direction, 'green', 10)
const draw_highlight_ray = (ctx, start, direction) => draw_raylike(ctx, start, direction, 'grey', 50)

const intersect_ray_circle = (ray, circle) => {
  const sqrt = Math.sqrt;
  const abs = Math.abs
  const sq = (x) => Math.pow(x,2)
  // move circle to origin
  const x1 = ray.start.x - circle.x
  const x2 = x1 + ray.direction.x
  const y1 = ray.start.y - circle.y
  const y2 = y1 + ray.direction.y
  const r = circle.r
  
  // intersection of circle at origin and line defined by two points
  // https://mathworld.wolfram.com/Circle-LineIntersection.html
  const dx = x2 - x1
  const dy = y2 - y1
  const dr = sqrt(sq(dx) + sq(dy))
  const D = x1*y2 - x2*y1
  const desc = sq(r) * sq(dr) - sq(D);
  // console.log("desc ", desc)
  if( desc < 0 )
    return "no intersection"
  const s = dy < 0 ? -1 : 1
  const x = (D*dy+s*dx*sqrt(desc)) / sq(dr)
  const x_ = (D*dy-s*dx*sqrt(desc)) / sq(dr)
  const y = (-1*D*dx+abs(dy)*sqrt(desc)) / sq(dr)
  const y_ = (-1*D*dx-abs(dy)*sqrt(desc)) / sq(dr)
  //console.log(`y = [ -1*${D}*${dx}+abs(${dy})*sqrt(${desc}) ] / ${dr}^2`) 
  //   console.log(`[${-1*D*dx}+${abs(dy)*sqrt(desc)}]/${sq(dr)}`)
              
  // move back from origin
  return [
    {x: x + circle.x, y: y + circle.y},
    {x: x_ + circle.x, y: y_ + circle.y},
  ]
}

const intersect_ray_line = (ray, line) => {
  return intersect_ray_ray( ray, { start: {x: line.x, y:0}, direction: {x:0, y:100} })
}

const intersect_ray_ray = (rayA, rayB) => {
  const x1 = rayA.start.x, y1 = rayA.start.y;
  const x2 = x1 + rayA.direction.x, y2 = y1 + rayA.direction.y;
  const x3 = rayB.start.x, y3 = rayB.start.y;
  const x4 = x3 + rayB.direction.x, y4 = y3 + rayB.direction.y;
  const D = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4)
  const x = ((x1*y2 - y1*x2)*(x3-x4) - (x1-x2)*(x3*y4 - y3*x4)) / D
  const y = ((x1*y2 - y1*x2)*(y3-y4) - (y1-y2)*(x3*y4 - y3*x4)) / D
  return [{x: x, y: y}]
}

const normal_at_circular_boundary = (point, circle, flip = false) => {
  // flip the normal for when we're doing concave intersections
  if(flip) {
     return {
      x: circle.x - point.x,
      y: circle.y - point.y
    }
  }
  // we assume the point is on the circle
  const normal = {
    x: point.x - circle.x,
    y: point.y - circle.y
  }
  return normal // I guess that's it... draw a line from the center of the circle to the point
}

const refracted_ray = (n1, n2, incoming, norm) => {
  // https://en.wikipedia.org/wiki/Snell's_law
  // snell's law: sin A2 / sin A1 = n1 / n2
  // n1 / n2 * sin A1 = sin A2
  // https://physics.stackexchange.com/questions/435512/snells-law-in-vector-form
  // vector form: norm x v2 = u( norm x v1), u = n1 / n2
  // moving in->out ie: n1 -> n2
  const sin = Math.sin
  const cos = Math.cos
  const asin = Math.asin
  const atan2 = Math.atan2
  const th_in = atan2(-incoming.y, -incoming.x)
  const th_norm = atan2(norm.y, norm.x)
  const th_1 = th_in - th_norm
  const th_norm_out = atan2(-norm.y, -norm.x)
  const th_2 = asin( n1 / n2 * sin(th_1))
  const th_out = th_2 + th_norm_out
  return {
    x: cos(th_out),
    y: sin(th_out)
  }
}

const dist_to = (A, B) => {
  return Math.sqrt( Math.pow(B.x - A.x, 2) + Math.pow(B.y - A.y,2))
}

const closest_intersection = (start, intrs) => {
  let ret = intrs[0]
  let shortest_distance = Infinity
  intrs.forEach((intr) => {
    const dist = dist_to(start, intr)
    if( dist < shortest_distance) {
      shortest_distance = dist
      ret = intr
    }
  })
  return ret
}

const cast_to_boundary = (ctx, cast_ray, boundary) => {
  let intrs
  if(boundary.circle) {
    intrs = intersect_ray_circle(
      cast_ray,
      boundary.circle
    )

    if( typeof(intrs) == "string")
       return intrs
  } else if( boundary.line) {
    intrs = intersect_ray_line(cast_ray, boundary.line)
  } else {
    return "Unknown boundary type"
  }
  const closest_intr = closest_intersection(cast_ray.start, intrs)
  // if( boundary.line) console.log(intrs)

  const n = boundary.normal_at(closest_intr)
  draw_normal(ctx, closest_intr, n)
  // if( boundary.line) console.log(closest_intr)

  const a = refracted_ray( boundary.n1, boundary.n2, cast_ray.direction, n)
  // draw_ray(ctx, closest_intr, a)
  
  return {
    start: closest_intr,
    direction: a
  }
}

const make_meniscus_boundaries = (index, thickness, first_face_x, first_face_r, second_face_r) => {
  const ffc = first_face_x + first_face_r
  const sfc = first_face_x + thickness + second_face_r
  const boundaries = [
    {
      n1: 1.0,
      n2: index,
      circle: {x: ffc, y: 0, r: first_face_r},
      normal_at: (p) => normal_at_circular_boundary(p, {x: ffc, y: 0, r: first_face_r}),
      x_crossing: (ffc - first_face_r)
    },
    {
      n1: index,
      n2: 1.0,
      circle: {x: sfc, y: 0, r: second_face_r},
      normal_at: (p) => normal_at_circular_boundary(p, {x: sfc, y: 0, r: second_face_r}),
      x_crossing: (sfc - second_face_r)
    }
  ]
  draw_aligned_circular_boundary(ctx, boundaries[0].x_crossing, boundaries[0].circle.r);
  draw_aligned_circular_boundary(ctx, boundaries[1].x_crossing, boundaries[1].circle.r);
  
  return boundaries
}

const make_biconvex_boundaries = (index, thickness, first_face_x, first_face_r, second_face_r) => {
  const ffc = first_face_x + first_face_r
  const sfc = first_face_x + thickness - second_face_r
  const boundaries = [
    {
      n1: 1.0,
      n2: index,
      circle: {x: ffc, y: 0, r: first_face_r},
      normal_at: (p) => normal_at_circular_boundary(p, {x: ffc, y: 0, r: first_face_r}),
      x_crossing: (ffc - first_face_r)
    },
    {
      n1: index,
      n2: 1.0,
      circle: {x: sfc, y: 0, r: second_face_r},
      normal_at: (p) => normal_at_circular_boundary(p, {x: sfc, y: 0, r: second_face_r}, true),
      x_crossing: (first_face_x + thickness)
    }
  ]
  draw_aligned_circular_boundary(ctx, boundaries[0].x_crossing, boundaries[0].circle.r);
  draw_aligned_circular_boundary(ctx, boundaries[1].x_crossing, -boundaries[1].circle.r);
  
  return boundaries
}

const make_biconcave_boundaries = (index, thickness, first_face_x, first_face_r, second_face_r) => {
  const ffc = first_face_x - first_face_r
  const sfc = first_face_x + thickness + second_face_r
  const boundaries = [
    {
      n1: 1.0,
      n2: index,
      circle: {x: ffc, y: 0, r: first_face_r},
      normal_at: (p) => normal_at_circular_boundary(p, {x: ffc, y: 0, r: first_face_r}, true),
      x_crossing: (ffc + first_face_r)
    },
    {
      n1: index,
      n2: 1.0,
      circle: {x: sfc, y: 0, r: second_face_r},
      normal_at: (p) => normal_at_circular_boundary(p, {x: sfc, y: 0, r: second_face_r}, false),
      x_crossing: (first_face_x + thickness)
    }
  ]
  draw_aligned_circular_boundary(ctx, boundaries[0].x_crossing, -boundaries[0].circle.r);
  draw_aligned_circular_boundary(ctx, boundaries[1].x_crossing, boundaries[1].circle.r);
  
  return boundaries
}

const draw_entire_diagram = (ctx) => {
  const canvas = document.getElementById('canvas')
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  
  // center line and end stops
  draw_axis(ctx);
  draw_aligned_vertical_boundary(ctx, mm(0));
  draw_aligned_vertical_boundary(ctx, mm(1000));

  // an image or a target or similar
  draw_aligned_vertical_boundary(ctx, mm(10));

  const boundaries = []
  let x1 = 0
  let x2 = 0
  let x3 = 0
  let length = mm(10)
  en1(()=>{
    x1 = mm(10) + dist1();
    boundaries.push( ...make_biconvex_boundaries(1.61, thk1(), x1, bnd1(), bnd2()) )
    length += dist1() + thk1()
  })
  en2(()=>{
    x2 = length + dist2();
    boundaries.push( ...make_biconcave_boundaries(1.62, thk2(), x2, bnd3(), bnd4()) )
    length += dist2() + thk2()
  })
  en3(()=>{
    x3 = length + dist3();
    boundaries.push( ...make_biconvex_boundaries(1.61, thk3(), x3, bnd5(), bnd6()) )
    length += dist3() + thk3()
  })
  
  // target
  draw_aligned_vertical_boundary(ctx, sensor())
  boundaries.push({
    n1: 1,
    n2: 1,
    line: {x: sensor(), y: 0},
    normal_at: (p) => ({x:-1, y:0})
  })

  // all the rays
  for( let y = mm(-50); y <= mm(50); y += (mm(50) - mm(-50))/num_rays()) {
    const cast_ray = {start: {x: mm(10), y: y}, direction: {x:10, y:0}}

    let next = cast_ray
    for( let i = 0; i < boundaries.length; i += 1) {
      draw_ray(ctx, next.start, next.direction)
      if( typeof(next) == "string")
        continue;
      if( Math.abs(next.start.y) > mm(75))
        continue;
      next = cast_to_boundary(ctx, next, boundaries[i])
    }
  }
  
  // tracer ray to measure effective focal length
  const cast_ray = { start: {x:mm(0), y:mm(15)}, direction: {x:1, y:0}}
  let next = cast_ray
  draw_highlight_ray(ctx, next.start, next.direction)
  for( let i = 0; i < boundaries.length; i += 1) {
    next = cast_to_boundary(ctx, next, boundaries[i])
  }
  draw_highlight_ray(ctx, next.start, { x: -next.direction.x, y: -next.direction.y} )
  const pint = intersect_ray_ray(cast_ray, next)
  draw_highlight_ray(ctx, {x: pint[0].x, y: pint[0].y}, {x:0, y:mm(-50)})
  
  // update labels
  update_measurements(length, pint[0].x, next.start.y)
}

const update_measurements = (length, efl, highlight_height) => {
  document.querySelector("span#focal_l").innerText = efl
  document.querySelector("span#bfd").innerText = sensor() - length
  document.querySelector("span#hlht").innerText = highlight_height
}

const setupSlider = (ctx, slider, initValue) => {
  // slider.min = 0
  // slider.max = max
  // slider.step = 10
  slider.value = initValue
  slider.addEventListener('input', () => draw_entire_diagram(ctx))
  return () => {
    return Number(slider.value)
  }
}

const setupCheckbox = (ctx, checkbox) => {
  checkbox.addEventListener('click', () => draw_entire_diagram(ctx))
  return (f) => {
    if(checkbox.checked) {
      f()
    }
  }
}

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

// const global_scale = (x) => (x * 2)
// const reverse_global_scale = (x) => ( x / 2 )
const mm = (x) => ( x)

const num_rays = setupSlider(ctx, document.querySelector("input#rays"), 4)
const bnd1 = setupSlider(ctx, document.querySelector("input#bnd1"), mm(40.1))
const bnd2 = setupSlider(ctx, document.querySelector("input#bnd2"), mm(537))
const bnd3 = setupSlider(ctx, document.querySelector("input#bnd3"), mm(47))
const bnd4 = setupSlider(ctx, document.querySelector("input#bnd4"), mm(40))
const bnd5 = setupSlider(ctx, document.querySelector("input#bnd5"), mm(235.5))
const bnd6 = setupSlider(ctx, document.querySelector("input#bnd6"), mm(37.9))
const dist1 = setupSlider(ctx, document.querySelector("input#dist1"), mm(10+100))
const dist2 = setupSlider(ctx, document.querySelector("input#dist2"), mm(10))
const dist3 = setupSlider(ctx, document.querySelector("input#dist3"), mm(10.8))
const thk1 = setupSlider(ctx, document.querySelector("input#thk1"), mm(6))
const thk2 = setupSlider(ctx, document.querySelector("input#thk2"), mm(1))
const thk3 = setupSlider(ctx, document.querySelector("input#thk3"), mm(6))
const en1 = setupCheckbox(ctx, document.querySelector("input#en1"))
const en2 = setupCheckbox(ctx, document.querySelector("input#en2"))
const en3 = setupCheckbox(ctx, document.querySelector("input#en3"))
const sensor = setupSlider(ctx, document.querySelector("input#sensor"), //mm(396))
                           //mm(10+100+ 6+10+1+10.8+6+85.3))
                           mm(10+100+ 6+10+1+10.8+6+85.3*2))
draw_entire_diagram(ctx)
              
            
!
999px

Console