Showing posts with label html. Show all posts
Showing posts with label html. Show all posts

Monday, August 01, 2016

Android: WebView

WebView demo to display HTML page in Activity and to enable Javascript


Adding Javascript interface to WebView to allow Javascript to communicate with and use Java classes

Thursday, February 05, 2015

Angular JS: how to share variables among different controllers or scope

Using services to create application data to be shared among different controllers or different scopes.
something like a global javascript variable in a single page app. not really session variable as the variable will reset after the page is refreshed.

HTML:

<html data-ng-app="demoApp" >
    <head>
        <title>Angular Demo</title>
    </head>
    <body data-ng-controller="MyController">
        <h1>Hello Angular</h1>
     
        <ul>
            <li><a ng-click="myMethod('clicked')" href="#/SecondPage">second page</a></li>
            <li><a href="#/ThirdPage">third page</a></li>
        </ul>
        <div ng-view></div>
        <script src="angular.min.js"></script>
        <script src="angular-route.min.js"></script>
        <script src="test01.js"></script>
    </body>
</html>


JS:

 var demoApp = angular.module('demoApp', ['ngRoute']);
// add service as dependencies
demoApp.controller('MyController', ['$scope', 'myService', '$route',
                        // add service as parameter
                        function($scope, myService, $route){
    console.log("MyController");
                         
    $scope.mydata = myService; // add service object to scope
 

    $scope.myMethod = function(special){
        console.log("myMethod called: " + special);
        myService.age++;
        myService.phone.price += 0.1;
        myService.addFriend("Friend " + myService.age);
        console.log(myService);
    };
}]);

//Define Routing for app
demoApp.config(['$routeProvider',
  function($routeProvider) {
    $routeProvider.
      when('/SecondPage', {
        templateUrl: 'second.html',
        controller: 'MyController' // can be different
    }).
      when('/ThirdPage', {
        templateUrl: 'third.html',
        controller: 'MyController' // can be different
      }).
      otherwise({
        redirectTo: '/SecondPage'
      });
}]);

// service
demoApp.factory('myService', function() {
    console.log("service starting");
    // object of this service
  var mydata = {
      // add properties
      name: "My Data",
      age: 30,
      friends: ["Tarth Bader", "Koda", "Kan zolo"],
      phone: {brand: "orange", model: "oPhone Plus", price:2000},
  };
    // add methods
    mydata.addFriend = function(friend){
        this.friends.push(friend);  
    };
  // return service
  return mydata;
});


second.html:
<div>{{ mydata.name }} is of {{mydata.age}}</div>
<ul>
    <li ng-repeat="friend in mydata.friends">{{friend}}</li>
</ul>

Angular JS: how to use separate html to layout the web app

different html to show different UI of the web app. 

HTML: 

<html data-ng-app="demoApp" >
    <head>
        <title>Angular Demo</title>
    </head>
    <body data-ng-controller="MyController">
        <h1>Hello Angular</h1>
        <input type="text" ng-model="name"/> {{name}}
        <div>
            {{age}}
        </div>
        <ul>
            <li><a ng-click="myMethod('clicked')" href="#/SecondPage">second page</a></li>
            <li><a href="#/ThirdPage">third page</a></li>
        </ul>
        <div ng-view><!-- the content from other html file will display here --></div>
        <script src="angular.min.js"></script>
        <script src="angular-route.min.js"></script>
        <script src="test01.js"></script>
    </body>
</html>


JS:

var demoApp = angular.module('demoApp', ['ngRoute']);
demoApp.controller('MyController', function($scope){
    console.log("MyController");
    $scope.hello = "Hello from AngJS";
    $scope.customers = ["dave", "larry"];
    $scope.age = 20;
    
    $scope.message = 'This is a new screen';
    
    $scope.myMethod = function(special){
        console.log("myMethod called: " + special);
        $scope.message = special;
    };
});

//Define Routing for app
demoApp.config(['$routeProvider',
  function($routeProvider) {
    $routeProvider.
      when('/SecondPage', {
        templateUrl: 'second.html',
        controller: 'MyController' // can be different controller. will instantiate new controller. different scope
    }).
      when('/ThirdPage', {
        templateUrl: 'third.html',
        controller: 'MyController
// can be different controller. will instantiate new controller. different scope
      }).
      otherwise({
        redirectTo: '/SecondPage'
      });
}]);

second.html:

<div>{{message}} </div> <!-- can add other HTML tag -->

third.html:

<div>{{hello}} </div> <!-- can add other HTML tag -->

Angular JS: starting out

basic hello world

HTML: 

<html data-ng-app="demoApp" >
    <head>
        <title>Angular Demo</title>
    </head>
    <body data-ng-controller="MyController">
        <h1>Hello Angular</h1>
        <input type="text" ng-model="name"/> {{name}}
        <div>
            {{age}}
        </div>
        
        <script src="angular.min.js"></script>
        <script src="test01.js"></script>
    </body>
</html>

JS:

var demoApp = angular.module('demoApp', [ ]);
demoApp.controller('MyController', function($scope){
    console.log("MyController");
    $scope.hello = "Hello from AngJS";
    $scope.customers = ["dave", "larry"];
    $scope.age = 20;
    
    $scope.myMethod = function(special){
        console.log("myMethod called: " + special);
        $scope.message = special;
    };
});

Friday, February 07, 2014

Phonegap / Cordova - set up and 1st app experience

follow installation steps
http://docs.phonegap.com/en/edge/guide_cli_index.md.html#The%20Command-Line%20Interface

download and install android adt-bundle. add tools and platform-tools dir in sys path
install nodejs
install apache ANT. add path to sys PATH
add Java JDK dir to JAVA_HOME sys variable

restart pc
command prompt
npm install -g cordova (if referring to phonegap docs online: for cordova,. just replace all "phonegap" with "cordova")

phonegap / cordova app installed in user dir, eg
C:\Users\{USERNAME}\AppData\Roaming\npm

cordova create hello com.example.hello "HelloWorld"
    $ cd hello
    $ cordova platform add android
    $ cordova build

still need to download cordova library for www & android. may be for first time use

open eclipse
"import existing Android code to workspace"

Clean project to remove errors and build and run. 



Wednesday, January 23, 2013

WebSocket: Alchemy - C# <-> javascript

Reference: http://divyen.wordpress.com/2012/06/13/html5-developing-websocket-server-using-c-sharp-dot-net/ 

Downloaded src code. http://alchemywebsockets.net/
Open it in Visual C# 2010 express
Managed to compile and get the Alchemy.dll

Created a new Console app project. added DLL
added the codes. https://gist.github.com/2976928
Build and then error....

Warning 8 - The referenced assembly "Alchemy" could not be resolved because it has a dependency on "System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" which is not in the currently targeted framework ".NETFramework,Version=v4.0,Profile=Client". Please remove references to assemblies not in the targeted framework or consider retargeting your project.

Go to Project Properties > application > Target Framework > .NET Framework 4
Click Yes for message box.

Build and Run. no more error.

added HTML codes. https://gist.github.com/a9409a82d2379d52e9af
run in chrome. HTML connected with websocket. clock ticking. cool.


Sunday, December 02, 2012

WebGL start

Reference: http://learningwebgl.com/blog/?p=28

download js matrix library: https://github.com/toji/gl-matrix/downloads

write the shader source code in a <script></script> tags

<script id="shader-fs" type="x-shader/x-fragment">
  precision mediump float;

  void main(void) {
    gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);
  }
</script>

<script id="shader-vs" type="x-shader/x-vertex">
  attribute vec3 aVertexPosition;

  uniform mat4 uMVMatrix;
  uniform mat4 uPMatrix;

  void main(void) {
    gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);
  }
</script>

variables needed in the javascript code

var triangleVertexPositionBuffer;
var squareVertexPositionBuffer;
var gl;
var shaderProgram;
var mvMatrix = mat4.create();
var pMatrix = mat4.create();

function webGLStart() {
    var canvas = document.getElementById("mycanvas");
    initGL(canvas);
    initShaders();
    initBuffers();

    gl.clearColor(0.0, 0.0, 0.0, 1.0);
    gl.enable(gl.DEPTH_TEST);

    drawScene();
}

function initGL(canvas) {
  try {
    gl = canvas.getContext("experimental-webgl");
    gl.viewportWidth = canvas.width;
    gl.viewportHeight = canvas.height;
  } catch(e) {
  }
  if (!gl) {
    alert("Could not initialise WebGL, sorry :-(");
  }
}

function initShaders() {
  var fragmentShader = getShader(gl, "shader-fs");
  var vertexShader = getShader(gl, "shader-vs");

  shaderProgram = gl.createProgram();
  gl.attachShader(shaderProgram, vertexShader);
  gl.attachShader(shaderProgram, fragmentShader);
  gl.linkProgram(shaderProgram);

  if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
    alert("Could not initialise shaders");
  }

  gl.useProgram(shaderProgram);
  
  shaderProgram.vertexPositionAttribute = gl.getAttribLocation(shaderProgram, "aVertexPosition");
  gl.enableVertexAttribArray(shaderProgram.vertexPositionAttribute);
  
  shaderProgram.pMatrixUniform = gl.getUniformLocation(shaderProgram, "uPMatrix");
  shaderProgram.mvMatrixUniform = gl.getUniformLocation(shaderProgram, "uMVMatrix");
}
function getShader(gl, id) {
    var shaderScript = document.getElementById(id);
    if (!shaderScript) {
        return null;
    }

    var str = "";
    var k = shaderScript.firstChild;
    while (k) {
        if (k.nodeType == 3)
            str += k.textContent;
        k = k.nextSibling;
    }

    var shader;
    if (shaderScript.type == "x-shader/x-fragment") {
        shader = gl.createShader(gl.FRAGMENT_SHADER);
    } else if (shaderScript.type == "x-shader/x-vertex") {
        shader = gl.createShader(gl.VERTEX_SHADER);
    } else {
        return null;
    }

    gl.shaderSource(shader, str);
    gl.compileShader(shader);

    if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
        alert(gl.getShaderInfoLog(shader));
        return null;
    }

    return shader;
}

function initBuffers() {
    triangleVertexPositionBuffer = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, triangleVertexPositionBuffer);
    var vertices = [
                    0.0,  1.0,  0.0,
                   -1.0, -1.0,  0.0,
                    1.0, -1.0,  0.0
               ];
    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
    triangleVertexPositionBuffer.itemSize = 3; // number of component to represent a vertex = 3; (x, y, z)
    triangleVertexPositionBuffer.numItems = 3; // number of vertices
}

function drawScene() {
gl.viewport(0, 0, gl.viewportWidth, gl.viewportHeight); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); mat4.perspective(45, gl.viewportWidth / gl.viewportHeight, 0.1, 100.0, pMatrix); mat4.identity(mvMatrix); mat4.translate(mvMatrix, [0, 0.0, -5.0]); gl.bindBuffer(gl.ARRAY_BUFFER, triangleVertexPositionBuffer); gl.vertexAttribPointer(shaderProgram.vertexPositionAttribute, triangleVertexPositionBuffer.itemSize, gl.FLOAT, false, 0, 0); setMatrixUniforms(); gl.drawArrays(gl.TRIANGLES, 0, triangleVertexPositionBuffer.numItems);
}

function setMatrixUniforms() {
    gl.uniformMatrix4fv(shaderProgram.pMatrixUniform, false, pMatrix);
    gl.uniformMatrix4fv(shaderProgram.mvMatrixUniform, false, mvMatrix);
}

HTML
<body onload="webGLStart()">
<canvas id="mycanvas" style="border: none;" width="500" height="500"></canvas>
</body>


Wednesday, March 07, 2012

Phonegap: HTML5 vs DOM/CSS

Tested and compared using HTML5 canvas drawing and DOM elements with CSS
strangely, when tested on an android 4 device, HTML5 canvas drawing cause the app to black out after a while.
using DOM elements and CSS2, seems ok.
performance pretty similar



Sunday, November 13, 2011

HTML5 + Javascript

few lessons learnt:
  1. <script /> is not valid. must use closing tag </script>
  2. made a simple mistake and debug like crazy:
    canvas = document.getElementById("test");
    context = canvas.getContext("2d");
    context.fillStyle("#FF0000"); //SHOULD have been context.fillStyle = "#FF0000";
    context.fillRect( 10, 20, 100, 50);

    More canvas reference: http://www.w3schools.com/html5/html5_ref_canvas.asp
  3. must use addEventListener for mouse input: canvas.addEventListener("mousedown", mDown, false);
  4. cannot get mouse (x,y) relative to canvas top left (0,0) so must manually calculate:
    var mouseX = (e.pageX -canvas.offsetLeft );
    var mouseY = (e.pageY -canvas.offsetTop);
  5. OOP
    function A() // create a class
    {
    this.v = 1; // fields or variables
    this.name = "haha";
    }
    A.prototype.constructor = A;
    A.prototype.m1 = function(){ // methods
    this.v++;
    }
    A.prototype.m2 = function(){
    this.v+=10;
    }
    // new class
B.prototype = new A();
B.prototype.constructor = B;

function B(){

  A.call(this); // call super class constructor if necessary

  this.x = 2;
}
B.prototype.m2 = function()
{
  A.prototype.m2.call(this); // call super class method if necessary
  // do additional stuff
}

var b = new B(); // create instance. BUT instantiation MUST be after the class declaration. debugged for a long time.