DEV Community

Sooraj (PS)
Sooraj (PS)

Posted on

Make it flash ⚡️ in HTML Canvas

Hey guys, after the Make it Rain with HTML Canvas, I am back with another fun canvas experiment. This time I created flashes of lightning using the line method of canvas. The creativity of canvas is unlimited and it's up to you to explore the possibilities.


(If pen doesn't run or is windowed, please click re-run. Sometimes there is an issue where the pen doesn't run.)

I just used the same concept when we draw a squiggly line on a piece of paper.

  • Draw a line.
  • Use the ending point of the previous line as the start of the next line.
  • Keep repeating this.

You can check out the code in the codepen above.

I added this configuration to play around with the types of bolts generated.

const interval = 3000;
const lightningStrikeOffset = 5;
const lightningStrikeLength = 100;
const lightningBoltLength = 5;
const lightningThickness = 4;
Enter fullscreen mode Exit fullscreen mode

interval - creates a lightning strike after the specified milliseconds
lightningStrikeOffset - determines how angled each bolt is. The more the offset, the more slanted the bolts look. I found 5 to be a good enough value.
lightningStrikeLength - determines how many bolts the strike will have.
lightningBoltLength - determines the length of a single line.
lightningThickness - determines the thickness of each line.

For the fade effect, I am just looping through the bolt and decreasing the opacity and thickness of the bolt.

for (let i = 0 ; i < lightning.length ; i++) {
  lightning[i].opacity -= 0.01;
  lightning[i].thickness -= 0.05;
  if (lightning[i].thickness <= 2) {
    lightning[i].end.y -= 0.05;
  }
  lightning[i].draw();
}
Enter fullscreen mode Exit fullscreen mode

Top comments (7)

Collapse
 
napatmiso profile image
Napatmiso

Can you make it work in Elememtor for Wordpress ?

Collapse
 
soorajsnblaze333 profile image
Sooraj (PS)

I can give it a try

Collapse
 
napatmiso profile image
Napatmiso

i like your works

Collapse
 
napatmiso profile image
Napatmiso

Do you only have HTML and CSS code? Your code is now locked on the screen. have to unlock

Thread Thread
 
soorajsnblaze333 profile image
Sooraj (PS)

Is the code not available ?

Collapse
 
andrewbaisden profile image
Andrew Baisden

Pretty cool. I read the title though "Make it flash" and I was worried that you found some crazy hacky way to combine Adobe Flash with HTML5 canvas 🤣

Collapse
 
soorajsnblaze333 profile image
Sooraj (PS)

Thanks :). Oops sorry for that. My last post on canvas was "Make it Rain" and the word that was catchy for this one was "Flash", So I used it for this.