Search code examples
javascriptandroidcanvassurfaceviewflicker

Flickering when drawing Android Surfaceview with Javascript Interface


There is a website where there are small scripts to manipulate a canvas. For example, some animated fractals with nice math. All code is in JavaScript.

Now I'm making an app to make this scripts work on Android, but because it is pure JavaScript, I'm not able to convert the code to Android-Java to manipulate the SurfaceView.

I made a SurfaceView and a (hidden) WebView. The Webview runs the JavaScript code of the animation. In the WebView I also injected an Interface (see JavascriptInterface), so that I can use Javascript to trigger functions that can manipulate the SurfaceView.

It works!!! But not perfectly.

The code I'm testing with will move this bars smoothly from left to right and back: enter image description here

function u(t){
    c.width=1920 // clear the canvas
    for(i=0;i<9;i++)
    x.fillRect(400+i*100+S(t)*300,400,50,200) // draw 50x200 rects
}

This happens on the site. This happens when I convert the JavaScript code to non-JavaScript Android code (Java).

It also works with JavaScript, but when I do that, the Surface begins to flicker. With one bar you already clearly see it, but with this 9 bars it is terrible.

I don't know what to do, because it works when I do it without JavaScript, but when I use JavaScript, it will flicker.

I hope there will be a solution for this.

Thanks in advance


Solution

  • I found out.

    I did lock the canvas before drawing one Rectangle and unlocked it directly after drawing, because SurfaceView has some buffering (Flickering while using surface view).

    Now I only lock the canvas before the u(t) function and only unlock it after it. That works.