Dynamic Canvas in Cordova or Phonegap

Posted By : Aman Goyal | 10-Apr-2017




What is HTML Canvas?

The HTML <canvas> element is used to draw graphics, on the mobile, via JavaScript.

Below the canvas tag is used to create a canvas element and u can set its property like width and height.

<canvas id="myCanvas" width="200" height="100"></canvas>

You can also set its height and width dynamically in javascript code. When you set its property dynamically then all the content in the canvas gets erased. i.e.

    var canvas = document.getElementById("myCanvas");



The <canvas> element is only a container for graphics. You must use JavaScript to actually draw any shape like rectangle, circle, square etc.

For Example this code is to draw a rectangle.

    context = canvas.get(0).getContext("2d"); //set the 2D context for the canvas.

    context.beginPath(); //start the context.

    context.rect(0, 225, 450, 35); //create a rectangle with rect(x,y,w,h) function..

    context.fillStyle = 'transparent'; //set the color for rectangle.

    context.fill(); //set the canvas with filled context.

Canvas lets you draw paths,text, boxes and add images in many different ways to make mobile app more attractive .


How to create a dynamic canvas:

1. First you have to create a background canvas element i.e.


2. Set its width and height as same as main canvas:



3. Create a context for it:


4. Draw the background canvas as same as main canvas.


Now you have two identical canvases. So you can easily extend the main canvas and add some extra graphics in this canvas, below is the code for that:


First draw the existing graphics (which is stored in backCanvas) in the main canvas and then add extra graphics.

        context.drawImage(backCanvas,0,0); //draw the image in the main Canvas.

        context.beginPath(); //start the main context again.

        context.rect(0, 225, 450, 35); //make a rectangle with rect(x,y,w,h) function.

        context.fillStyle = 'transparent'; //set the style

        context.fill(); //fill the context in the canvas

        context.fillStyle = 'black'; //set the style color.

        context.lineWidth = 2; //set the context line width

        context.font = '16pt Calibri'; //set the context font

        context.fillText(signaturerName, 10, 235); //here u can add graphics in the main canvas context.




About Author

Author Image
Aman Goyal

Aman is an Android developer. Quite good in building logics. Languages he is good in C, C++, java. He is keen on learning new things, flexible, and adaptive to the new environment. Also, have some experience in marketing.

Request for Proposal

Name is required

Comment is required

Sending message..