Sunday, December 27, 2020

Published December 27, 2020 by with 0 comment

Making a CSS Flashlight Effect Using Conic-gradients

This is just a quick tutorial of conic-gradients showing a flashlight effect with very little code.

The basic idea here is to use a conic-gradient and do the following:

  • set it to be the flashlight color and fairly transparent for the bright area (yellow from -25 to 25 degrees in the example here)
  • set it to be dark and fairly opaque for the dark area (black with 95% opacity from 25 to 335 degrees in the example here)
  • make the flashlight layer(s) fixed position and sit on top of the page
  • to keep it from starting as a point, offset it (vertical location of 110% in the example here puts it 10% below the bottom of the page)
And that's's actually really simple. Here is a working example on top of a dummy html page:

It's really clean and requires no javascript. It's probably possible to make it cleaner. An obvious question you might have is 'can I make a flashlight that moves with the mouse?' and the answer is sure...simply set the gradient position to the cursor location (this requires javascript but is simple):

All that took was adding a listener to the page for mouse or touch movements, updating --X and --Y variables on those events, and setting the conic-gradient position to be var(--X) var(--Y). Simple and looks pretty cool.



Post a Comment