html5-canvas Clear canvas with gradient.


Example

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);
bgGrad.addColorStop(0,"#0FF");
bgGrad.addColorStop(1,"#08F");

// Every time you need to clear the canvas
ctx.fillStyle = bgGrad;
ctx.fillRect(0,0,canvas.width,canvas.height);

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)