DOCTYPE html html lang en head meta charset UTF 8 meta name viewport content width device width initial scale 1 0 title Canvas Fire Effect title style canvas display block margin 0 auto background color black style head body canvas id fireCanvas width 320 height 320 canvas script const canvas document getElementById fireCanvas const ctx canvas getContext 2d const width canvas width const height canvas height let fire new Array width height fill 0 let colours function Colour r g b this r r this g g this b b Initialize the fire and colour palette function initPattern for let i 0 i 256 i colours i new Colour 0 0 0 for let i 0 i 32 i black to blue colours i b i 1 blue to red colours i 32 r i 3 colours i 32 b 64 i 1 red to yellow colours i 64 r 255 colours i 64 g i 3 yellow to white colours i 96 r 255 colours i 96 g 255 colours i 96 b i 2 colours i 128 r 255 colours i 128 g 255 colours i 128 b 64 i 2 colours i 160 r 255 colours i 160 g 255 colours i 160 b 128 i 2 colours i 192 r 255 colours i 192 g 255 colours i 192 b 192 i colours i 224 r 255 colours i 224 g 255 colours i 224 b 224 i function pattern Randomize the bottom row of the fire array for let i 0 i width 1 i fire width height 1 i Math random 0 5 255 0 Move fire upwards for let y 0 y height 1 y for let x 0 x width 1 x const src y 1 width x const dst y width x let val fire src fire src x 0 1 0 fire src x width 1 1 0 fire src width val Math floor val 3 96 val Math min val 255 fire dst val 0 val 1 0 function render const imageData ctx createImageData width height const data imageData data for let i 0 i fire length i const col colours fire i const index i 4 data index col r data index 1 col g data index 2 col b data index 3 255 Alpha channel ctx putImageData imageData 0 0 function update pattern render requestAnimationFrame update initPattern update script body html
2 colours i 192 r 255 colours i 192 g 255 colours i 192 b 192 i colours i 224 r 255 colours i 224 g 255 colours i 224 b 224 i function pattern Randomize the bottom row of the fire array for let i 0 i width 1 i fire width height 1 i Math random 0 5 255 0 Move fire upwards for let y 0 y height 1 y for let x 0 x width 1 x const src y 1 width x const dst y width x let val fire src fire src x 0 1 0 fire src x width 1 1 0 fire src width val Math floor val 3 96 val Math min val 255 fire dst val 0 val 1 0 function render const imageData ctx createImageData width height const data imageData data for let i 0 i fire length i const col colours fire i const index i 4 data index col r data index 1 col g data index 2 col b data index 3 255 Alpha channel ctx putImageData imageData 0 0 function update pattern render requestAnimationFrame update initPattern update script body html