html5-canvas Clear canvas with gradient.


Rather than use clearRect which makes all pixels transparent you may want a background.

To clear with a gradient

// create the background gradient once
var bgGrad = ctx.createLinearGradient(0,0,0,canvas.height);

// Every time you need to clear the canvas
ctx.fillStyle = bgGrad;

This is about half as quick 0.008ms as clearRect 0.004ms but the 4millions of a second should not negatively impact any realtime animation. (Times will vary considerably depending on device, resolution, browser, and browser configuration. Times are for comparison only)