Saturday, November 23, 2013

Simple Captcha using java script

Here you get simple way to apply captcha for your site using java script.

Steps to drive captcha on html page:

1)Assign canvas tag and image tag  on html page with width and height  whatever size you want,
2)Generate Random String of Alpha-numeric character.
3)Convert that random string to canvas->Image and print it on page.

For reCaptcha 

1)just clear the previous canvas and refill it with random string.


 Step 1: //here is html code :


  <div>
  <canvas id='textCanvas' width=100 height=40></canvas>
  <img id='image'>
  <br>
<img id="refresh_captcha" src="/oltapp/ButtonImages/Refresh.png" onClick="randomString();"/>
  </div>

Step 2: //java script


  <script type="text/javascript">
    
     // captcha when document get reload
 
         $(document).ready(function(){
         $("#refresh_captcha").click();
     
         });


      function randomString() {
   
           // Genrate random string
     
           var randomstring = '';

            var chars = "0123456789ABCDEFGHIJKL!@#$%^&*()MNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";

        var string_length = 5;  //Length of Captcha

        for (var i=0; i<string_length; i++) {
            var rnum = Math.floor(Math.random() * chars.length);
            randomstring += chars.substring(rnum,rnum+1);
        }

        // Getting canvas variable
        var tCtx = document.getElementById('textCanvas').getContext('2d'),
        imageElem = document.getElementById('image');



        tCtx.font= "normal 24px Verdana";  //set text fonts option for  canvas,html5
canvas: Text Option

        tCtx.strokeStyle = "#000000";    //
html5 canvas: Text Option
        
        tCtx.clearRect(0,0,100,40);        //Clear previous Canvas for redraw our captcha

        tCtx.strokeText(randomstring,30,20,70);  //Stroke random string to canvas
 
        tCtx.textBaseline = "middle";                  //html5 canvas: Text Option,line in middle of text

        imageElem.src = tCtx.canvas.toDataURL(); // provide canvas url to image src
 
        console.log(imageElem.src);  //image

    }
</script>

now we having captcha when document get ready and when click on refresh button,From HTML5 Canvas option you can set background image or another text style in captcha and having different options to make your captcha attractive.

example captcha:



For more HTML5 Canvas:Text Option - http://createdynamicgraph.blogspot.in/
 

HTML5 Canvas: Text Options

It is possible to draw text on an HTML5 canvas, using various fonts, sizes and colors. 

The look of the text is controlled by these 2D Context font property. In addition you will need to set either the fillStyle or strokeStyle 2D Context property, depending on whether you want to draw filled or stroked text.

To draw the text you use either the fillText() or strokeText() function. The fillText()
Here is a simple code example: 

var canvas  = document.getElementById("ex1");
var context = canvas.getContext("2d");

context.font      = "normal 36px Verdana";
context.fillStyle = "#000000";
context.fillText("HTML5 Canvas Text", 50, 50);

context.font        = "normal 36px Arial";
context.strokeStyle = "#000000";
context.strokeText("HTML5 Canvas Text", 50, 90);
 

    Here is the result when drawn on a canvas:
 
 
 

 

 Fonts and Styles

When drawing text on an HTML5 canvas you have to set what font to use. This is done by setting the value of the 2D Context font property. This property is a string with CSS compliant values, of the format:
[font style][font weight][font size][font face]
For instance:
context.font = "normal normal 20px Verdana";
 
Here are the values you can set for each part of the font string: 

font style normal
italic
oblique
inherit
font weightnormal
bold
bolder
lighter
auto
inherit
100
200
300
400
500
600
700
800
900
font size A size in pixels e.g 12px, 20px etc.
font face A font face (family), e.g. verdana, arial, serif, sans-serif, cursive, fantasy, monospace etc.
Note that not all values may be supported by each browser. You will have to test the values you plan to use before relying on them.
Here is another example: 

"italic bold 36px Arial"

Drawing Text

When drawing text on an HTML5 canvas you can draw either filled or outlined text, as shown earlier. You do so using the 2D Context functions fillText() and strokeText(). These functions are defined like this:

 
fillText   (textString, x, y [,maxWidth]);
strokeText (textString, x, y [,maxWidth]);

The textString parameter is the text to draw.
The x and y represents the location where the text is be drawn. The x parameter is where the text starts. The y parameter is where the text is located vertically, but exactly how it is represented depends on the text baseline. The text baseline is covered in a later section.
The maxWidth text is covered in the section below.
Here is a code example:
 
context.font      = "36px Verdana";
context.fillStyle = "#000000";
context.fillText("HTML5 Canvas Text", 50, 50);

Text Max Width

The optional maxWidth parameter tells the canvas that the text cannot take up more space horizontally than the given parameter value. If the text is too wide to fit into the maxWidth, the text is compressed in the width. It is not cut off. Here is a code example that draws the same text with and without maxWidth:

context.font      = "36px Verdana";
context.fillStyle = "#000000";
context.fillText("HTML5 Canvas Text", 50, 50);
context.fillText("HTML5 Canvas Text", 50, 100, 200);
 
Here is what the two texts look like, when drawn on an HTML5 canvas:
As you can see, the second text is compressed in its width to fit the maxWidth of 200 pixels.

Text Color

The color of either filled or stroked text is set using the fillStyle and strokeStyle properties of the 2D Context, like with any other shape. I will not get into more detail with those properties here.

Measuring Text Width

The 2D Context object has a function that can measure the width in pixels of a text. It cannot measure the height. The function is called measureText(). Here is a code example:

var textMetrics = context.measureText("measure this");

var width = textMetrics.width; 
 
Measuring the width of a text can be used to calculate if a text string fits into a certain space etc.

Text Baseline

The text baseline determines how the y parameter of the fillText() and strokeText() is interpreted. In other words, where the text is positioned vertically, and how this position is interpreted. Notice, that there might be minor differences in how the browsers interpret this property too.
The text baseline is set using the textBaseline property of the 2D Context. Here are the values it can take, and what they mean:
top The text is aligned based on the top of the tallest glyph in the text.
hanging The text is aligned based on the line the text seems to hang from. This is almost identical to top, and in many cases you cannot see the difference.
middle The text is aligned according to the middle of the text.
alphabetic The bottom of vertically oriented glyphs, e.g. western alphabets like the latin
ideographic The bottom of horizontally oriented glyphs.
bottom The text is aligned based on bottom of the glyph in the text, that extends lowest down in the text.
Here is an example that draws text using the same y value (75) for all texts, but uses a different baseline for each text drawn. A line is drawn a y=75 to show you how the text is baselined around that y value.



For the curious, here is the code that generates the above graphics:

context.stokeStyle = "#000000";
context.lineWidth  = 1;
context.beginPath();
context.moveTo(  0, 75);
context.lineTo(500, 75);
context.stroke();
context.closePath();

context.font      = "16px Verdana";
context.fillStyle = "#000000";

context.textBaseline = "top";
context.fillText("top", 0, 75);

context.textBaseline = "hanging";
context.fillText("hanging", 40, 75);

context.textBaseline = "middle";
context.fillText("middle", 120, 75);

context.textBaseline = "alphabetic";
context.fillText("alphabetic", 200, 75);

context.textBaseline = "ideographic";
context.fillText("ideographic", 300, 75);

context.textBaseline = "bottom";
context.fillText("bottom-glyph", 400, 75);
 

Convert Text to Image using java script on html page

Here you find out way to show your text into image on html page just in few lines  of  js code.

//here is your html body ,where your text image genrate

   <div>
          <canvas id='textCanvas' width=100 height=40></canvas>
          <img id='image'>
           <br>
           <input type="button" onClick="textToImage();" >
   </div>


// here is your java script function which generate text into image

<script>

function textToImage()
{

var textCanvas= document.getElementById('textCanvas').getContext('2d'),  //Assign canvas variable,

imageElem = document.getElementById('image');                    //Image variable,

textCanvas.font= "normal 24px Verdana";                         //HTML5 Canvas:Text option for text field

textCanvas.strokeStyle = "#000000";

textCanvas.clearRect(0,0,100,40);               //clear previous canvas for redrawing image    

textCanvas.strokeText('input text',30,20,70);   //fill text into canvas

imageElem.src = textCanvas.canvas.toDataURL();  //providing canvas url to image src

console.log(imageElem.src);

}
</script>

now you have image of text that you have entered in strokeText(); 

///HTML5 Canvas:Text option for text field

[font style][font weight][font size][font face]
 
example: 
context.font = "normal normal 20px Verdana"; 


we have lot of option in HTML5 Canvas .which help to draw different structure.
you can see different option for HTML5 Canvas :Text  in next blog.
 

Genrate Random Key/Alpha-Numeric String using java Script

In this blog I am going to show you how to generate Random String/key of alpha-numeric values using java script, which may help us in many way like generate random key, any strong random password e.t.c 

Here is function which generate random string.

var string=' ';

 function randomString(){
    
var random_string=' ';  // Empty Random String
      
 var chars = "0123456789ABCDEFGHIJKL!@#$%^&* ()MNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";  // Characters from where random string generate

var string_length = 5;  //Length of random string

for (var i=0; i<string_length; i++) {
            var rnum = Math.floor(Math.random() * chars.length);
            random_string += chars.substring(rnum,rnum+1);  //generate random string
        }

string=random_string;  //here is your generated random string
alert(random_string);
}

enjoy with your random key. :)