Spot the bug - #103: Canvas Loop

My canvas circle refuses to actually show up, why

<canvas id="c" width="200" height="200"></canvas>
<script>
  const canvas = document.getElementById('c');
  const ctx = canvas.getContext;
  ctx.beginPath();
  ctx.arc(100, 100, 50, 0, Math.PI * 2);
  ctx.fillStyle = 'purple';
  ctx.fill();
</script>

Reply with what is broken and how you would fix it.

Do you need to close the path?

Not path closure, different problem entirely. canvas. getContext is missing the call and the argument. That’s grabbing the method reference, not invoking it, so ctx ends up undefined and every draw call after just fails silently with no error in the console, which is the annoying part.

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

Fix that and check if the circle renders before you even think about closePath(). Arc fills don’t strictly need it anyway since fill() closes the shape for you implicitly.

1 Like

Spot the Bug answer: ctx is assigned the getContext function reference itself instead of calling it, so ctx is not a rendering context and has no drawing methods

The fix:

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

Why:
canvas.getContext is a method that must be invoked with the context type argument to return a CanvasRenderingContext2D object. Without the parentheses, ctx just holds the function itself, so calling ctx.beginPath() etc. would throw errors and nothing gets drawn.


Nobody got this one. It was a sneaky one.

Close but not quite:

@kirupa - The real bug is that ctx is missing the getContext(‘2d’) call, not a missing closePath (which isn’t needed for a full circle anyway).