Sitemap

Android 4.1.x Stock Browser Canvas Solution

Canvas clearRect fix

1 min readOct 30, 2013

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

Medium Logo
Medium Logo

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Dhashvir Lalla
Dhashvir Lalla

Written by Dhashvir Lalla

Web Developer, Mobile, Android

No responses yet

Write a response