Create WebGL Based Native Android App in 5 simple steps
![Create WebGL Based Native Android App in 5 Simple Steps webgl android](https://prototechsolutions.com/wp-content/uploads/2017/03/Create-WebGL-Based-Native-Android-App-in-5-Simple-Steps.png)
Using WebGL with Native Android
WebGL is a powerful and widely used JavaScript framework/API for 3D rendering, and Android is the platform which has a large community and allows quick and handy access. The WebView API in Android acts as a bridge between these two, So we can put all our 3D rendering logic into HTML files along with a library (Three.js), and render it inside the Android’s WebView.
Here are the steps to set-up your application with WebGL Android:
Before we start, store your WebGL page (HTML and Javascript files) in the assets directory of the application.
Step 1: Set up the Android development environment
Create an Android application, and in the resource layout file of your MainActivity class add the WebView :
activity_main.xml
Step 2: Create a new Android project
Now, Initialize the WebView in your MainActivity.java:
public class MainActivity extends AppCompatActivity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
App.getComponent().inject(this);
setContentView(R.layout.activity_main);
WebView webView = findViewById(R.id.modelWebView);
}
}
Step 3: Configure the project for WebGL
In order to use THREE.js or any other JavaScript library/code, we need to enable JavaScript on the WebView, this can be done by adding this simple line after the WebView is initialized:
webView.getSettings().setJavascriptEnabled(true);
Note: Whenever using JavaScript application, this is needed to be set explicitly.
Step 4: Integrate WebGL into your Android app
Loading the URL of the base HTML file from the assets folder:
Regardless of the actual name, the assets folder is always accessed by the name “android_asset”
webView.loadUrl(“file:///android_asset/sample.html”);
Browser output:
Application output:
Step 5: Load and display WebGL content in your app
WebView also allows you to call any JavaScript method present within the page, through loadUrl() method:
Ex.: webView.loadUrl("javascript: cube.material.color.setRGB(0,100,0);");
After execution:
What can you do with this app?
Anything you can do in HTML, CSS, JavaScript and WebGL, almost all those things are possible here too. So go ahead and create interactive eye-candy WebGL pages and use them in your Android apps to suffice the need of vast Android user base, make them happy & increase your sales too !!!