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");

    canvas[0].height=250;

    canvas[0].width=400;

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.

        backCanvas=document.createElement("canvas");

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

        backCanvas.height=canvas[0].height;

        backCanvas.width=canvas[0].width;

3. Create a context for it:

        backContext=backCanvas.getContext("2d");

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

        backContext.drawImage(canvas[0],0,0);

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:

        canvas[0].height=canvas[0].height+40;

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.

 

 

 

Request for Proposal

Recaptcha is required.

Sending message..