exebook
exebook

Reputation: 33900

What is difference between fillRect(0,0,0,1) and clearRect()

Is there any difference between:

ctx.fillStyle = "rgba(0, 0, 0, 1)";
ctx.fillRect(0, 0, 100, 100)

and

ctx.clearRect(0, 0, 100, 100)

Any kind of difference in performance or resulting image or canvas data?

Upvotes: 14

Views: 5458

Answers (1)

user1693593
user1693593

Reputation:

(Updated to correspond to OPs changes in question:) fillRect() with ctx.fillStyle = "rgba(0, 0, 0, 1)"; will fill the region with opaque pixels, in this case black (note alpha is a normalized value [0,1]).

clearRect() does the opposite, "clearing" all pixels so that the bitmap becomes transparent (technically the region is filled with black transparent pixels).

clearRect() is optimized while fillRect() is bound to compositing/blending rules (Porter-Duff) so the former is faster. What this means is that clearRect is free to fill a region directly only based on current transformation, while fillRect has to go through the compositing/blending formula whatever that is set to (globalCompositeOperation) in addition.

That is of course in theory - it will depend on browser implementation. Here is a simple performance test showing that in Chrome filling is faster than clearing (I am not sure what goes on with Chrome and canvas nowadays), but in Firefox clearing is many times faster than filling, both significantly faster than Chrome:

perfsnap

In browsers which supports the opacity flag of the context, you can disable alpha if you don't need it, to make canvas respond even faster (the alpha here being blending with the element itself and composition with the browser background). You will see speed improvements in particular the Opera browser, but also Firefox and Chrome support this flag. To disable alpha:

var ctx = canvas.getContext("2d", {alpha: false});

Upvotes: 17

Related Questions