Android 4.1.x Stock Browser Canvas Solution

Canvas clearRect fix

There is currently an issue on Android 4.1.x and some 4.2.x stock browsers where the canvas clearRect function doesn’t work correctly sometimes.

The issue occurs predominantly when using clearRect in a setTimeout or in the request animation frame.
The solution that has been suggested is to use is

canvas.width = canvas.width;

This works but also causes some browsers to crash especially if used in a game loop running at 60fps.

I have found a better solution that does not cause browsers to crash.

The following code fixes the canvas clearRect issue but if clearing very often it causes a bit of a delay in the clearing:

canvas.clearRect(0, 0, w, h);
canvas.style.visibility = ‘hidden’;
// Force a change in DOM
canvas.offsetHeight;
// Cause a repaint to take play
canvas.style.visibility = ‘inherit’;
// Make visible again

If you use the following it fixes the delayed clearing but on certain devices using this causes anti-aliasing of the canvas when reattaching the canvas into DOM.

canvas.clearRect(0, 0, w, h);
canvas.style.display = ‘none’;
// Detach from DOM
canvas.offsetHeight;
// Force the detach
canvas.style.display = ‘inherit’;
// Reattach to DOM

A nice way to implement this is to override the native clearRect functionality and add the 3 lines of code needed to force the clearing.

I have tested this solution on the devices listed below:

Devices tested on Android 4.1.1 & 4.1.2:
Samsung S3
Samsung Galaxy Note 2
Samsung S3 Mini

Fix needed on 4.2.x devices
Samsung Galaxy Note 8
Samsung Galaxy Nexus