Search code examples
javascripthtmlcanvasdrawingmasking

HTML canvas dynamic masking


Simply put, I'm drawing a red line across the screen on an HTML canvas and I would like a moving white circle to only be visible on the current portion of the line that it's touching. I read a lot about canvas masking but I haven't run into a similar situation to use as a reference. The entire circle should never be visible, only the portion of it that's covering the line or lines if there happen to be more than one. Any suggestions? Thanks!


Solution

  • I'm glad to hear you're learning about the more advanced html Canvas capabilities!

    I suggest you next read about context.globalCompositeOperation.

    https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Canvas_tutorial/Compositing

    Compositing allows you to manipulate how new drawings are drawn relative to existing drawings.

    In particular, the source-atop compositing mode should be helpful in your situation because new drawings (your circle) will only appear where it intersects existing drawings (your line).

    Good luck with your project!