Showing posts with label HTML. Show all posts
Showing posts with label HTML. Show all posts

May 1, 2013

jQuery Context Menu


In this tutorial I am sharing my newly created jQuery Plugin, jQuery Simple Context Menu.


jQuery Simple Context Menu


GITHUB REPO :
https://github.com/nirajmchauhan/jquery-simple-context-menu




Currently this plugin accepts two paramenters:

  • Custom HTML - You have to give entire HTML code with proper attributes in it wrapped inside ul


  • Simple HTML - You have to pass href link and the text to be shown.



Simple HTML usage
Include the jquery file, you can download this from github.


[js]

jQuery(function($){
$(document).ready(function(){

$('#Simple').simpleContextMenu({
options : {
'Home' : '#',
'About Us' : '#',
'Services' : '#',
'Contact Us' : '#'
}
});

});
});

[/js]



Inside options you need to pass text and the link, the above code will generate a HTML in following format :


[html]
<ul>
<li>
<a href="#">Home</a>
</li>
<li>
<a href="#">About Us</a>
</li>
<li>
<a href="#">Services</a>
</li>
<li>
<a href="#">Contact Us</a>
</li>
</ul>
[/html]



Custom HTML usage


[js]

jQuery(function($){
$(document).ready(function(){

$('#CustomHTML').simpleContextMenu({
html: '<div class="dropdown clearfix"><ul style="display: block; position: static; margin-bottom: 5px; *width: 180px;" aria-labelledby="dropdownMenu" role="menu" class="dropdown-menu"><li><a href="#" tabindex="-1">Action</a></li><li><a href="#" tabindex="-1">Another action</a></li><li><a href="#" tabindex="-1">Something else here</a></li><li class="divider"></li><li><a href="#" tabindex="-1">Separated link</a></li></ul></div>'
});

});
});

[/js]



Inside html you need to pass entire html which will be the context menu. Above I am using bootstrap.




Both parameters cannot be used together, use only one at a time. You can have multiple context menus on a single page. Check out the demo and fork me.

Dec 15, 2012

Website content management system – what is it all about?

CMS or the Content management system, in simple words can be explained as PC
software that helps you to amend, alter, make public and maintain the contents from
the central interface end. Initially CMS was designed with the purpose of simplifying
the complex task of writing codes of various versions and to ease up the development
process more flexible and handy. This type of software helps to manage system that
controls and manages the complete content with the help of a workflow procedure
including a collaborative environment.


CMS


CMS helps to centralize data edit, publish and modify at the single back end interface.
This web CMS technique is best used to be in charge of active set of web materials that
are made available online such as websites, media files and document.


Different types of CMS


We have three major types of Content Management System (CMS) namely, online
processing, offline processing and hybrid systems. These processes are being used
in the implementation procedure to describe the deployment pattern for Web CMS via
presentation templates that provide a structural content pattern for your web page.


Online processing system is all about implementing templates requisite condition.
Usually a web page HTML is being generated during a visitor’s entry or when the
page is being pulled off from web cache. It is known that most of the open source web
content management system has the capability to support add-ons that offers the
required support including blogs, forums, web stores, etc. It’s being referred to as add-
ons, widgets, modules, or extensions with open source of paid license model.


Offline processing system is something that is also termed as static site generators.
Pre-process all the content by implementing the right templates ahead of issuing to
generate your web pages. As pre-processing system does not call for server to make
use of the templates at the right time, they subsist as design-time tools.


Hybrid systems
There are systems where both online and offline techniques are being implemented.
Some systems write their exec codes to move on with dynamic HTML condition where
CMS is not deployed on all servers. While the other types of Hydrid systems are either
offline or online base on the functionality.

Jan 15, 2012

Google Maps Server Side Geocoding Using PHP and Infobox Fully AJAX

Recently I got a new project of real estate where I had to display about 1000 of projects on the google map. I was having the address of 1000 projects, so I started with my php and js code. When I coded and started testing, I found that on the map only 20-30 markers were shown. When I debugged I found an error of OVER_QUERY_LIMIT. I started googling and found that Geocoding has some limitations on converting address into lat long. In API there are two ways of getting LAT LONG.

  • Client Side

  • Server Side


Client side geocoding has some limitation of 20 queries per minute or sec. Server side geocoding also has limitations but after 2500 queries.

google-map

 

So in this tutorial we will first code our simple HTML then PHP and finally our AJAX.

HTML is pretty short and simple.

Filename: index.php

 
[html]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Google Server Side Geocoding Using PHP and Infobox Fully AJAX</title>

<style>
#wrapper{width:1002px; margin:0px auto;}
#loading {
position: relative;
text-align: center;
top: 45%;
}
</style>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false&language=en"></script>
<script type="text/javascript" src="http://google-maps-utility-library-v3.googlecode.com/svn-history/r290/trunk/infobox/src/infobox.js"></script>
<script type="text/javascript" src="http://localhost:8080/gmap/google.js"></script>

</head>

<body>
<div id="wrapper">
<div id="googlemaps" style="width:500px; height:500px;position:relative;border:1px solid #888888;margin: 0 auto;">
</div>
</div>
</body>
</html>
[/html]
 

Here we are leaving a blank div, which will be filled with our google map.

In our PHP code, we can call the addresses either from database or an array. I am using array in this tutorial.

In server side geocoding we actually pass our address through an URL which returns a CSV or json formatted data.

Then we extract the lat long from this data using explode function and store it in an array. This array is passed to our AJAX function in json formatted.

Filename: gmap.php
 
[php]
<?php
$address = array(
"1" => array("Address" => "Bandra, Mumbai, India" , "Name" => "Bandra"),
"2" => array("Address" => "Khar, Mumbai, India" , "Name" => "Khar"),
"3" => array("Address" => "Santacruz, Mumbai, India" , "Name" => "Santacruz"),
"4" => array("Address" => "Andheri, Mumbai, India" , "Name" => "Andheri"),
"5" => array("Address" => "Jogeshwari, Mumbai, India" , "Name" => "Jogeshwari"),
"6" => array("Address" => "Goregaon, Mumbai, India" , "Name" => "Goregaon"),
"7" => array("Address" => "Malad, Mumbai, India" , "Name" => "Malad"),
"8" => array("Address" => "Kandivili, Mumbai, India" , "Name" => "Kandivili"),
"9" => array("Address" => "Borivali, Mumbai, India" , "Name" => "Borivali"),
"10" => array("Address" => "Dahisar, Mumbai, India" , "Name" => "Dahisar"),
"11" => array("Address" => "Mira Road, Mumbai, India" , "Name" => "Mira Road"),
"12" => array("Address" => "Bhayander, Mumbai, India" , "Name" => "Bhayander"),
"13" => array("Address" => "Naigaon, Mumbai, India" , "Name" => "Naigaon"),
"14" => array("Address" => "Vasai, Mumbai, India" , "Name" => "Vasai"),
"15" => array("Address" => "Nallasopara, Mumbai, India" , "Name" => "Nallasopara"),
"16" => array("Address" => "Virar, Mumbai, India" , "Name" => "Virar"),
"17" => array("Address" => "Churchgate, Mumbai, India" , "Name" => "Churchgate"),
"18" => array("Address" => "Charni Road, Mumbai, India" , "Name" => "Charni Road"),
"18" => array("Address" => "Grant Road, Mumbai, India" , "Name" => "Grant Road"),
"19" => array("Address" => "Dadar, Mumbai, India" , "Name" => "Dadar"),
"20" => array("Address" => "Mahim, Mumbai, India" , "Name" => "Mahim"),
"21" => array("Address" => "King Circle, Mumbai, India" , "Name" => "King Circle"),
"22" => array("Address" => "Worli, Mumbai, India" , "Name" => "Worli"),
);

foreach($address as $Idx => $key){
$addr = urlencode($key['Address']);
$url = 'http://maps.google.com/maps/geo?q='.$addr.'&output=csv&sensor=false';
$get = file_get_contents($url);
$records = explode(",",$get);
$lat = $records['2'];
$lng = $records['3'];

$data[] = array('Lat'=>$lat, 'Lng'=>$lng, 'Name'=>$key['Name']);

}
echo json_encode($data);
?>
[/php]
 

Now we call our ajax function on the load of the page.

Filename: google.js

 
[js]
jQuery(function($) {
$(document).ready(function() {
getAdress();//On page load initialize our map function.
});
});
[/js]
 

We will use infobox to create stylish markers and windows. When we load our function on page load, this function consists with an AJAX call, which gets the data from our gmap.php file, which will be in JSON formatted. We convert it into normal array using JSON.parse(). Finally we throw this array into foreach loop and store the lat, long values in a variable.

 

These lat long variables are also an array so one more for loop and then we pass it to our createmarker function which will be creating the markers on map.

Filename: google.js

 
[js]
function getAdress() {
jQuery(function($) {
$("#googlemaps").html('<div id="loading"><img src="loading.gif" /></div>');
$.ajax( {
url : "gmap.php",
type : "GET",
success : function(data) {
// get the data string and convert it to a JSON object.
var jsonData = JSON.parse(data);
var latitude = new Array();
var longitude = new Array();
var name = new Array();
var logo = new Array();
var i = 0;
var j = 0;
var k = 0;
$.each(jsonData, function(Idx, Value) {
$.each(Value, function(x, y) {
//Creating an array of latitude, logitude
if(x == 'Lat')
{
i = i + 1;
latitude[i] = y;
}
if(x == 'Lng')
{
j = j + 1;
longitude[j] = y;
}
if(x == 'Name')
{
k = k + 1;
name[k] = y;
}
});
});
$("#googlemaps").html('');
//passing the array to initialize function, where our map will be formed
initialize(latitude,longitude,name, logo);
}
});
});
}
function initialize(latitude,longitude, name, logo) {

//initialization of map.
var geocoder = new google.maps.Geocoder();
var initCenter = new google.maps.LatLng(19.0759837, 72.87765590000004);//By default Mumbai is loaded
var map = new google.maps.Map(document.getElementById('googlemaps'), {
zoom: 11,
center: initCenter,
mapTypeId: google.maps.MapTypeId.ROADMAP
});

//initialization of infowindow
var infoWindow = new google.maps.InfoWindow;
var boxText = document.createElement("div");

var j = 1;
var image = new google.maps.MarkerImage('icon-home.gif');//Setting the marker image

//Infowindow is fully customizable, here we make our infowindow stylish by adding css styles to it.

var myOptions = {
content: boxText
,disableAutoPan: false
,maxWidth: 181
,zIndex: null
,boxStyle: {
background: "#000000"
,color: "#fff"
,width: "auto"
,padding: "10px"
,borderRadius: "20px"
,fontFamily: "Tahoma"
,opacity: "0.5"
}
,infoBoxClearance: new google.maps.Size(1, 1)
,isHidden: false
,pane: "floatPane"
,closeBoxURL: ""
,enableEventPropagation: false
};
var ib = new InfoBox(myOptions);

//Final for loop for creating the markers
for(var a = 1; a < latitude.length; ++a)
{
createMarkers(geocoder, map, name[a], latitude[a], longitude[a], ib, image);
}
}


function createMarkers(geocoder, map, name, latitude, longitude, ib, image) {

//Setting the onclick marker function
var onMarkerClick = function() {
var marker = this;
var latLng = marker.getPosition();
ib.setContent(name);
ib.open(map, marker);
};

google.maps.event.addListener(map, 'click', function() {
ib.close();
});

//In array lat long is saved as an string, so need to convert it into int.
var lat = parseFloat(latitude);
var lng = parseFloat(longitude);

var marker = new google.maps.Marker({
map: map,
icon: image,
position: new google.maps.LatLng(lat, lng),
title: name
});

//Adding the marker.
google.maps.event.addListener(marker, 'click', onMarkerClick);
}
[/js]
 

This above js file can be minified further, there are other ways of getting the data, but I found this very simple and easy. You can check the live demo. Any suggestions are welcome. Happy geocoding

Dec 9, 2011

JQuery Popup | JQuery Slide Popup

Now a day’s JQuery’s are used almost in all websites. In today’s tutorial I am going to share a new way to show a pop up message. Everyone is getting bored with typical fade in fade out pop up messages. So let’s make it interesting with a pinch of jquery and css.

In this tutorial we are going to make two javascript functions which will be used to slide in and slide out a div.

[js]
function openOffersDialog() {
$('#overlay').fadeIn('fast', function() {
$('#boxpopup').css('display','block');
$('#boxpopup').animate({'left':'30%'},500);
});
}

function closeOffersDialog(prospectElementID) {
$(function($) {
$(document).ready(function() {
$('#' + prospectElementID).css('position','absolute');
$('#' + prospectElementID).animate({'left':'-100%'}, 500, function() {
$('#' + prospectElementID).css('position','fixed');
$('#' + prospectElementID).css('left','100%');
$('#overlay').fadeOut('fast');
});
});
});
}
[/js]

In the first function we are making a call to a div to fadeIn and in that fade in function we are sliding our popup from right to left.

The next function is used to slide the function from center of the screen to the extreme left side so it appears us to be disappeared. In this function we also set the overlay div to fadeout.

So let’s construct with our HTML part.

[html]
<body onload="openOffersDialog();">
<div id="wrapper">
<div id="overlay" class="overlay"></div>
<a onclick="openOffersDialog();">Click Here To See The PopUp</a>
<div id="boxpopup" class="box">
<a onclick="closeOffersDialog('boxpopup');" class="boxclose"></a>
<div id="content">
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum.
</div>
</div>
</div>
</body>
[/html]

This was a small tutorial on sliding a popup without using any JQuery UI and making it different from other popups.

UPDATE: CHECK THE NEW DEMO FOR LOAD THE POPUP ON CLICK. THIS WILL NOT LOAD THE POPUP ON LOAD OF PAGE



 

Sep 11, 2011

JQuery Color Changing Background | JQuery Continous Color Change | JQuery Rainbow

In today's tutorial, I am going to share an easy way to change the background color of a page in infinite loops. In other words, change the background to rainbow.


Concept:The actual logic behind changing the color in infinite loops, is to get infinite colors. So trick is simple, take a RGB pattern and keep on changing the color code. So for that a logic of RGB code is written in jquery.color.js

So the index javascript consists of two major codes.

[html]

var rainbow = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';

[/html]

We are creating a variable named as rainbow and setting its value to rgb(random numbers). They are calculated and by using math.round and math.floor functions, the decimals are removed from it.

The last important thing is to append the color to the background of an HTML element.

[html]
$('#welcome').animate( { backgroundColor: rainbow }, 1000);
[/html]
The most important thing is how to get into infinite loops?????

Simple, within the function declare the same function, which will give us infinite loop.

So the entire javascript function will be.

[html]
<script type="text/javascript">// <![CDATA[
$(document).ready(function() {

spectrum();

function spectrum(){
var rainbow = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';
$('#welcome').animate( { backgroundColor: rainbow }, 1000);
spectrum();
}

});
// ]]></script>
[/html]

Aug 11, 2011

How To Make A GAME In HTML 5 | How To Build A Game With HTML 5

download



Final Output:


Running Ball

HTML 5 is growing at the lightning speed, none of the languages in web development has grew up in this speed. Today we are going to make a simple game in HTML 5 by using Box2D and HTML 5 Canvas.


But before that, the question is



What is BOX2D?
Box2D is an open source and popular engine that simulates 2D physics for making games and applications. Primarily written in C++, it has been converted to numerous languages by community contributors.

This tutorial is divided into 5 simple steps, so lets get started



STEP - 1 Folder Structure


First of all we need to download the box2d engine for our html 5, you can download it from here. Next we create the file and folder structure. Just follow the image of file folder structure and copy paste them in respective places.
Folder Structure


After the setup of files, we will add necessary files to the html file that is index.html



[html]
<!--[if IE]><script src="lib/excanvas.js"></script><![endif]--><script type="text/javascript" src="lib/prototype-1.6.0.2.js"></script>
<!-- box2djs -->
<script type="text/javascript" src="js/box2d/common/b2Settings.js"></script><script type="text/javascript" src="js/box2d/common/math/b2Vec2.js"></script>
<script type="text/javascript" src="js/box2d/common/math/b2Mat22.js"></script><script type="text/javascript" src="js/box2d/common/math/b2Math.js"></script>
<script type="text/javascript" src="js/box2d/collision/b2AABB.js"></script><script type="text/javascript" src="js/box2d/collision/b2Bound.js"></script>
<script type="text/javascript" src="js/box2d/collision/b2BoundValues.js"></script><script type="text/javascript" src="js/box2d/collision/b2Pair.js"></script>
<script type="text/javascript" src="js/box2d/collision/b2PairCallback.js"></script><script type="text/javascript" src="js/box2d/collision/b2BufferedPair.js"></script>
<script type="text/javascript" src="js/box2d/collision/b2PairManager.js"></script><script type="text/javascript" src="js/box2d/collision/b2BroadPhase.js"></script>
<script type="text/javascript" src="js/box2d/collision/b2Collision.js"></script><script type="text/javascript" src="js/box2d/collision/Features.js"></script>
<script type="text/javascript" src="js/box2d/collision/b2ContactID.js"></script><script type="text/javascript" src="js/box2d/collision/b2ContactPoint.js"></script>
<script type="text/javascript" src="js/box2d/collision/b2Distance.js"></script><script type="text/javascript" src="js/box2d/collision/b2Manifold.js"></script>
<script type="text/javascript" src="js/box2d/collision/b2OBB.js"></script><script type="text/javascript" src="js/box2d/collision/b2Proxy.js"></script>
<script type="text/javascript" src="js/box2d/collision/ClipVertex.js"></script><script type="text/javascript" src="js/box2d/collision/shapes/b2Shape.js"></script>
<script type="text/javascript" src="js/box2d/collision/shapes/b2ShapeDef.js"></script><script type="text/javascript" src="js/box2d/collision/shapes/b2BoxDef.js"></script>
<script type="text/javascript" src="js/box2d/collision/shapes/b2CircleDef.js"></script><script type="text/javascript" src="js/box2d/collision/shapes/b2CircleShape.js"></script>
<script type="text/javascript" src="js/box2d/collision/shapes/b2MassData.js"></script><script type="text/javascript" src="js/box2d/collision/shapes/b2PolyDef.js"></script>
<script type="text/javascript" src="js/box2d/collision/shapes/b2PolyShape.js"></script><script type="text/javascript" src="js/box2d/dynamics/b2Body.js"></script>
<script type="text/javascript" src="js/box2d/dynamics/b2BodyDef.js"></script><script type="text/javascript" src="js/box2d/dynamics/b2CollisionFilter.js"></script>
<script type="text/javascript" src="js/box2d/dynamics/b2Island.js"></script><script type="text/javascript" src="js/box2d/dynamics/b2TimeStep.js"></script>
<script type="text/javascript" src="js/box2d/dynamics/contacts/b2ContactNode.js"></script><script type="text/javascript" src="js/box2d/dynamics/contacts/b2Contact.js"></script>
<script type="text/javascript" src="js/box2d/dynamics/contacts/b2ContactConstraint.js"></script><script type="text/javascript" src="js/box2d/dynamics/contacts/b2ContactConstraintPoint.js"></script>
<script type="text/javascript" src="js/box2d/dynamics/contacts/b2ContactRegister.js"></script><script type="text/javascript" src="js/box2d/dynamics/contacts/b2ContactSolver.js"></script>
<script type="text/javascript" src="js/box2d/dynamics/contacts/b2CircleContact.js"></script><script type="text/javascript" src="js/box2d/dynamics/contacts/b2Conservative.js"></script>
<script type="text/javascript" src="js/box2d/dynamics/contacts/b2NullContact.js"></script><script type="text/javascript" src="js/box2d/dynamics/contacts/b2PolyAndCircleContact.js"></script>
<script type="text/javascript" src="js/box2d/dynamics/contacts/b2PolyContact.js"></script><script type="text/javascript" src="js/box2d/dynamics/b2ContactManager.js"></script>
<script type="text/javascript" src="js/box2d/dynamics/b2World.js"></script><script type="text/javascript" src="js/box2d/dynamics/b2WorldListener.js"></script>
<script type="text/javascript" src="js/box2d/dynamics/joints/b2JointNode.js"></script><script type="text/javascript" src="js/box2d/dynamics/joints/b2Joint.js"></script>
<script type="text/javascript" src="js/box2d/dynamics/joints/b2JointDef.js"></script><script type="text/javascript" src="js/box2d/dynamics/joints/b2DistanceJoint.js"></script>
<script type="text/javascript" src="js/box2d/dynamics/joints/b2DistanceJointDef.js"></script><script type="text/javascript" src="js/box2d/dynamics/joints/b2Jacobian.js"></script>
<script type="text/javascript" src="js/box2d/dynamics/joints/b2GearJoint.js"></script><script type="text/javascript" src="js/box2d/dynamics/joints/b2GearJointDef.js"></script>
<script type="text/javascript" src="js/box2d/dynamics/joints/b2MouseJoint.js"></script><script type="text/javascript" src="js/box2d/dynamics/joints/b2MouseJointDef.js"></script>
<script type="text/javascript" src="js/box2d/dynamics/joints/b2PrismaticJoint.js"></script><script type="text/javascript" src="js/box2d/dynamics/joints/b2PrismaticJointDef.js"></script>
<script type="text/javascript" src="js/box2d/dynamics/joints/b2PulleyJoint.js"></script><script type="text/javascript" src="js/box2d/dynamics/joints/b2PulleyJointDef.js"></script>
<script type="text/javascript" src="js/box2d/dynamics/joints/b2RevoluteJoint.js"></script><script type="text/javascript" src="js/box2d/dynamics/joints/b2RevoluteJointDef.js"></script>
[/html]

Next, we will create two more scripts file inside the /js/ folder directory, named as  "box2dutils.js" and "game.js" respectively




  • box2dutils.js – This files is a copy and paste from some other online demos that come with box2dlib, and it is very important for drawing functions.

  • game.js – By the name it will be easy to recognize, it the actual game, where platform, keyboard input etc functions are set.


Copy paste the following code in "box2dutils.js" file



[html]
function drawWorld(world, context) {
for (var j = world.m_jointList; j; j = j.m_next) {
drawJoint(j, context);
}
for (var b = world.m_bodyList; b; b = b.m_next) {
for (var s = b.GetShapeList(); s != null; s = s.GetNext()) {
drawShape(s, context);
}
}
}
function drawJoint(joint, context) {
var b1 = joint.m_body1;
var b2 = joint.m_body2;
var x1 = b1.m_position;
var x2 = b2.m_position;
var p1 = joint.GetAnchor1();
var p2 = joint.GetAnchor2();
context.strokeStyle = '#00eeee';
context.beginPath();
switch (joint.m_type) {
case b2Joint.e_distanceJoint:
context.moveTo(p1.x, p1.y);
context.lineTo(p2.x, p2.y);
break;

case b2Joint.e_pulleyJoint:
// TODO
break;

default:
if (b1 == world.m_groundBody) {
context.moveTo(p1.x, p1.y);
context.lineTo(x2.x, x2.y);
}
else if (b2 == world.m_groundBody) {
context.moveTo(p1.x, p1.y);
context.lineTo(x1.x, x1.y);
}
else {
context.moveTo(x1.x, x1.y);
context.lineTo(p1.x, p1.y);
context.lineTo(x2.x, x2.y);
context.lineTo(p2.x, p2.y);
}
break;
}
context.stroke();
}
function drawShape(shape, context) {
context.strokeStyle = '#000000';
context.beginPath();
switch (shape.m_type) {
case b2Shape.e_circleShape:
{
var circle = shape;
var pos = circle.m_position;
var r = circle.m_radius;
var segments = 16.0;
var theta = 0.0;
var dtheta = 2.0 * Math.PI / segments;
// draw circle
context.moveTo(pos.x + r, pos.y);
for (var i = 0; i < segments; i++) {
var d = new b2Vec2(r * Math.cos(theta), r * Math.sin(theta));
var v = b2Math.AddVV(pos, d);
context.lineTo(v.x, v.y);
theta += dtheta;
}
context.lineTo(pos.x + r, pos.y);

// draw radius
context.moveTo(pos.x, pos.y);
var ax = circle.m_R.col1;
var pos2 = new b2Vec2(pos.x + r * ax.x, pos.y + r * ax.y);
context.lineTo(pos2.x, pos2.y);
}
break;
case b2Shape.e_polyShape:
{
var poly = shape;
var tV = b2Math.AddVV(poly.m_position, b2Math.b2MulMV(poly.m_R, poly.m_vertices[0]));
context.moveTo(tV.x, tV.y);
for (var i = 0; i < poly.m_vertexCount; i++) {
var v = b2Math.AddVV(poly.m_position, b2Math.b2MulMV(poly.m_R, poly.m_vertices[i]));
context.lineTo(v.x, v.y);
}
context.lineTo(tV.x, tV.y);
}
break;
}
context.stroke();
}

function createWorld() {
var worldAABB = new b2AABB();
worldAABB.minVertex.Set(-1000, -1000);
worldAABB.maxVertex.Set(1000, 1000);
var gravity = new b2Vec2(0, 300);
var doSleep = true;
var world = new b2World(worldAABB, gravity, doSleep);
return world;
}

function createGround(world) {
var groundSd = new b2BoxDef();
groundSd.extents.Set(1000, 50);
groundSd.restitution = 0.2;
var groundBd = new b2BodyDef();
groundBd.AddShape(groundSd);
groundBd.position.Set(-500, 340);
return world.CreateBody(groundBd)
}

function createBall(world, x, y) {
var ballSd = new b2CircleDef();
ballSd.density = 1.0;
ballSd.radius = 20;
ballSd.restitution = 1.0;
ballSd.friction = 0;
var ballBd = new b2BodyDef();
ballBd.AddShape(ballSd);
ballBd.position.Set(x,y);
return world.CreateBody(ballBd);
}

function createBox(world, x, y, width, height, fixed, userData) {
if (typeof(fixed) == 'undefined') fixed = true;
var boxSd = new b2BoxDef();
if (!fixed) boxSd.density = 1.0;

boxSd.userData = userData;

boxSd.extents.Set(width, height);
var boxBd = new b2BodyDef();
boxBd.AddShape(boxSd);
boxBd.position.Set(x,y);
return world.CreateBody(boxBd)
}
[/html]

Don't worry I ll explain the code further.


Now we move on to our next step



Step 2 - Game Development


Open the index.html file, which we created in the first step, after adding the head part, insert the canvas code between the body tag



[html]<canvas id="game" width="600" height="400"></canvas>[/html]

Next we have to add the reference of the two javascripts file which we created just now. So in index.html, within the head tag, add the following code in it.



[html]
<script type="text/javascript" src="js/box2dutils.js"></script><script type="text/javascript" src="js/game.js"></script>
[/html]

Now lets start developing our game, so open game.js file and add the following code in it.



[html]
// some variables that we gonna use in this demo
var initId = 0;
var player = function(){
this.object = null;
this.canJump = false;
};
var world;
var ctx;
var canvasWidth;
var canvasHeight;
var keys = [];

// HTML5 onLoad event
Event.observe(window, 'load', function() {
world = createWorld(); // box2DWorld
ctx = $('game').getContext('2d'); // 2
var canvasElm = $('game');
canvasWidth = parseInt(canvasElm.width);
canvasHeight = parseInt(canvasElm.height);
initGame(); // 3
step(); // 4

// 5
window.addEventListener('keydown',handleKeyDown,true);
window.addEventListener('keyup',handleKeyUp,true);
});
[/html]

OK, now its time for explanation of code now


BOX2DWorld is the available class from the core of box2d.Its major and simple function is to combine everything into one class. In this box2DWorld, we have the bodies definition and collisions manager of our game.


Now open the game.js and box2dutils.js and search for the function createWorld() in box2dutils.js file.



[html]
function createWorld() {
// here we create our world settings for collisions
var worldAABB = new b2AABB();
worldAABB.minVertex.Set(-1000, -1000);
worldAABB.maxVertex.Set(1000, 1000);
// set gravity vector
var gravity = new b2Vec2(0, 300);
var doSleep = true;
// init our world and return its value
var world = new b2World(worldAABB, gravity, doSleep);
return world;
}
[/html]

Its really simple to make such box2DWorld


Now again back to game.js file.


Now copy paste the following code in game.js file



[html]
function initGame(){
// create 2 big platforms
createBox(world, 3, 230, 60, 180, true, 'ground');
createBox(world, 560, 360, 50, 50, true, 'ground');

// create small platforms
for (var i = 0; i < 5; i++){
createBox(world, 150+(80*i), 360, 5, 40+(i*15), true, 'ground');
}

// create player ball
var ballSd = new b2CircleDef();
ballSd.density = 0.1;
ballSd.radius = 12;
ballSd.restitution = 0.5;
ballSd.friction = 1;
ballSd.userData = 'player';
var ballBd = new b2BodyDef();
ballBd.linearDamping = .03;
ballBd.allowSleep = false;
ballBd.AddShape(ballSd);
ballBd.position.Set(20,0);
player.object = world.CreateBody(ballBd);

}

Inside <code>box2dutils.js</code>, we've created a function, called <code>createBox</code>. This creates a static rectangle body.

function createBox(world, x, y, width, height, fixed, userData) {
if (typeof(fixed) == 'undefined') fixed = true;
//1
var boxSd = new b2BoxDef();
if (!fixed) boxSd.density = 1.0;
//2
boxSd.userData = userData;
//3
boxSd.extents.Set(width, height);

//4
var boxBd = new b2BodyDef();
boxBd.AddShape(boxSd);
//5
boxBd.position.Set(x,y);
//6
return world.CreateBody(boxBd)
}
[/html]

A Box2DBody has some unique characteristics:




  • It can be static (not affected by collisions impacts), kinematic (it isn't affected by collisions, but it can be moved by your mouse, for example), or dynamic (interacts with everything)

  • Must have a shape definition, and should indicate how the object appears

  • May have more than one fixture, which indicates how the object will interact with collisions

  • Its position is set by the center of your object, not the left top edge as many other engines do.


Reviewing the above code:



  1. Here we are creating a shape, which can be a square or rectangle or any other geometry shape. And also we setup the density(the actual movement of the object)

  2. We setup the userData, usually we setup graphics objects here, but for this game, we just setup strings that will be the identifier of the type of the object for collisions.

  3. Setup half of the size of our box.

  4. We create the body definition, and add to it the box shape definition.

  5. Setup the position.

  6. Create the body in the world and return its value.


Creating The Player Object


Paste the following code in game.js file



[html]
var ballSd = new b2CircleDef();
ballSd.density = 0.1;
ballSd.radius = 12;
ballSd.restitution = 0.5;
ballSd.friction = 1;
ballSd.userData = 'player';
var ballBd = new b2BodyDef();
ballBd.linearDamping = .03;
ballBd.allowSleep = false;
ballBd.AddShape(ballSd);
ballBd.position.Set(20,0);
player.object = world.CreateBody(ballBd);
[/html]

So now we have created body.
We have used simple steps




  1. Created Shape, Fixture and Sensor Definition.

  2. Created Body Definition

  3. Added body into the shape

  4. Created body in the world.


Simple isn't it?


So Now if we run our code, it will give us a blank white screen.


Don't panic, till now we have just setup Box2, and always remember



Box2D doesn't render; it only calculates physics.

Step 3 - Rendering Time


Now we will render the box2dworld.


Open game.js file and add the following code in it:



[html]
function step() {

var stepping = false;
var timeStep = 1.0/60;
var iteration = 1;
// 1
world.Step(timeStep, iteration);
// 2
ctx.clearRect(0, 0, canvasWidth, canvasHeight);
drawWorld(world, ctx);
// 3
setTimeout('step()', 10);
}
[/html]

In the above code we have intructed box2dworld to achieve the following things




  1. To perform physics calculations.

  2. To clear the canvas screen and draw again on it.

  3. And to run the step() function in every 10 milliseconds.


Now if you run the code, you will see the canvas with a running ball.


Running Ball


drawWorld in box2dutils.js


Open box2dutils.js file and add the following code in it.



[html]
function drawWorld(world, context) {
for (var j = world.m_jointList; j; j = j.m_next) {
drawJoint(j, context);
}
for (var b = world.m_bodyList; b; b = b.m_next) {
for (var s = b.GetShapeList(); s != null; s = s.GetNext()) {
drawShape(s, context);
}
}
}
[/html]

The above written function is a debug function which will draw our world into the canvas, by using the graphics API provided by HTML5's Canvas API.


The very first loop will draw all joints.


The second loop will draw all bodies.



[html]
function drawShape(shape, context) {
context.strokeStyle = '#000000';
context.beginPath();
switch (shape.m_type) {
case b2Shape.e_circleShape:
{
var circle = shape;
var pos = circle.m_position;
var r = circle.m_radius;
var segments = 16.0;
var theta = 0.0;
var dtheta = 2.0 * Math.PI / segments;
// draw circle
context.moveTo(pos.x + r, pos.y);
for (var i = 0; i < segments; i++) {
var d = new b2Vec2(r * Math.cos(theta), r * Math.sin(theta));
var v = b2Math.AddVV(pos, d);
context.lineTo(v.x, v.y);
theta += dtheta;
}
context.lineTo(pos.x + r, pos.y);

// draw radius
context.moveTo(pos.x, pos.y);
var ax = circle.m_R.col1;
var pos2 = new b2Vec2(pos.x + r * ax.x, pos.y + r * ax.y);
context.lineTo(pos2.x, pos2.y);
}
break;
case b2Shape.e_polyShape:
{
var poly = shape;
var tV = b2Math.AddVV(poly.m_position, b2Math.b2MulMV(poly.m_R, poly.m_vertices[0]));
context.moveTo(tV.x, tV.y);
for (var i = 0; i < poly.m_vertexCount; i++) {
var v = b2Math.AddVV(poly.m_position, b2Math.b2MulMV(poly.m_R, poly.m_vertices[i]));
context.lineTo(v.x, v.y);
}
context.lineTo(tV.x, tV.y);
}
break;
}
context.stroke();
}
[/html]

Here we're looping through every vertices of the object and drawing it with lines.



Step 4 - Interactivity


In this step we will instruct the game by our keyboard events.
Add the following code to game.js file



[html]
function handleKeyDown(evt){
keys[evt.keyCode] = true;
}

function handleKeyUp(evt){
keys[evt.keyCode] = false;
}

// disable vertical scrolling from arrows</pre>
<img src="http://net.tutsplus.com/wp-includes/images/smilies/icon_smile.gif" alt=":)" />
<pre>
document.onkeydown=function(){return event.keyCode!=38 && event.keyCode!=40}
[/html]

With the help of an array we are handling the UpKey and the DownKey event. With document.onkeydown, we disable the browser's native vertical scrolling function for up and down arrows.
If you have played a html5 game and jumped during the game, the game goes off screen, but in our game, it won't



[html]handleInteractions(); [/html]

And outside, declare the function:



[html]
function handleInteractions(){
// up arrow
// 1
var collision = world.m_contactList;
player.canJump = false;
if (collision != null){
if (collision.GetShape1().GetUserData() == 'player' || collision.GetShape2().GetUserData() == 'player'){
if ((collision.GetShape1().GetUserData() == 'ground' || collision.GetShape2().GetUserData() == 'ground')){
var playerObj = (collision.GetShape1().GetUserData() == 'player' ? collision.GetShape1().GetPosition() :  collision.GetShape2().GetPosition());
var groundObj = (collision.GetShape1().GetUserData() == 'ground' ? collision.GetShape1().GetPosition() :  collision.GetShape2().GetPosition());
if (playerObj.y < groundObj.y){
player.canJump = true;
}
}
}
}
// 2
var vel = player.object.GetLinearVelocity();
// 3
if (keys[38] && player.canJump){
vel.y = -150;
}

// 4
// left/right arrows
if (keys[37]){
vel.x = -60;
}
else if (keys[39]){
vel.x = 60;
}

// 5
player.object.SetLinearVelocity(vel);
}
[/html]

The most complicated code in the above function is the first one, where we are checking the collision and writing some if else condition to determine the shape one or shape two.


On the second commented line (2), we retrieve the LinearVelocity of the player.


The third and forth commented sections verify if arrows are being pressed, and adjust the velocity vector(speed), accordingly.


In the fifth section, we setup the player with the new velocity vector.


Till now interactions are done, but if you run it now, it will only keep on jumping.



Step 5 - "You Win" Message


Add the code below to the beginning of your LinearVelocity function:



[html]
if (player.object.GetCenterPosition().y > canvasHeight){
player.object.SetCenterPosition(new b2Vec2(20,0),0)
}
else if (player.object.GetCenterPosition().x > canvasWidth-50){
showWin();
return;
}
[/html]

In this the first condition determines that if the player falls then it should be placed agin to the starting point.


The second condition is used to state if the player is in the final platform then display the winning function, which is below



[html]
function showWin(){
ctx.fillStyle = '#000';
ctx.font = '30px verdana';
ctx.textBaseline = 'top';
ctx.fillText('Yes! you made it!', 30, 0);
ctx.fillText('Thank You, www.webstutorial.com', 30, 30);
ctx.fillText('HTML 5 Rocks', 30, 60);
}
[/html]

And that's it, you have just made your own simple adventure game in HTML5.


Credit:NetTuts

download

Aug 2, 2011

Learn PHP | PHP Tutorials | PHP Lessons | Part 1

Learn PHP – Tutorial

(Part 1) Lesson -1

In this lesson we will focus on the following topics:-

  1.   PHP Basics

  2.   Server Side Scripting

  3.   PHP tags

  4.   The “echo ” command

  5.   Creating your first script


Let’s get started right away.

PHP Basics:

What is PHP ?

  • PHP is PHP:Hypertext  Preprocessor.

  • It is a programming language that is specially designed for creating Dynamic websites.

  • PHP language is flexible, making it easy to learn even if you have not done any programming in the past.


For example you could use PHP to show the current date and time on top of each page on your website.

[php]

Today’s date and time

The date is <!--?php  echo date(‘j F Y’); ?-->
and the time is <!--?php echo date(‘H:i:s’); ?-->

[/php]

  • Also it can easily process data submitted in HTML form and talk to various database systems( like SQL, MySQL, ..etc.) allowing generation of webpage based on SQL query.


 

Server Side Scripting:

  •         The most important concept to learn when starting out with PHP is where exactly it fits in a web environment. When you understand this, you will understand what PHP can and cannot do.



  •         A PHP module attached to your web server is telling the server that files with a particular extension (i.e. time.php) should be examined for PHP code. It processes instructions sent in a webpage by the client machine i.e. any PHP code found in the page is executed, thereby code is replaced by the output before it is sent back to the client’s web browser.  For eg. time.php file. The file contains basic HTML code along with PHP to display the current date and time. Here the PHP module in the server searches the file for the PHP code and replaces the code with the output. The following output is shown on the screen.


Output:-

The date is 1 August 2011 and the time is 14:29:54

  •          Once the page is downloaded, PHP plays no further part until another web page is requested by the client’s web browser.



  •          One thing PHP is not capable of doing is Client-Side-Validation. Now you’ll wonder what is Client-Side-Validation ?.


Consider a form(form.php) where you have to fill in all your details like Name, Address, Zip-code etc.

Client-Side-Validation checks value entered in a particular field like “Name:-..” meets certain criteria before moving to the next field i.e. in simple words you cannot enter your “Zip-code” in the area where you have to enter your “Name:-..” .

So to check the value entered is proper and valid is Client-Side-Validation. Client-Side-Validation can be achieved when PHP works with JavaScript.

  •          The beauty of PHP is that it doesn’t rely on the web browser at all. Your script will run the same no matter what browser you use. There is no need to worry about enabling JavaScript on your browser.


 

PHP tags:

Today is <?php echo date (‘j F Y’); ?>

  •          Above code is from a PHP driven web page that displays the current date

  •          The tag “<?php ”  tells that everything that follows is program code rather than HTML until the closing tag “?>”

  •          The “echo” command tells PHP to display the very next item on the screen. “echo” is used for printing output on the screen, “echo” is similar to “print” statement.

  •          The “date(‘j F Y’);” produces the formatted version of date, containing the day as “j” month as “F” and “Y” as the year.



  •           Also note that anything that appears outside the PHP tag will be displayed on the screen. As seen in the above line of code where “Today is:” which is outside the PHP tag is displayed on the output screen just before the generated date.


Note:-  In this tutorial PHP code appears inside tags that look like this “<?php ”

            and “?>”. Other tag styles can be used such as

“<%” – Asp tag style..

“<script language = “PHP”>” – the script tag.

The “echo ” command:

  • The “echo” command is used to sent output to the browser


For example:-

[php]
<?php /* php code to display date
and time */
echo “The time is ”;       / use of double quotes /
echo date(‘H:i:s’);
echo ‘and the date is ’      / use of single quotes /
echo date(‘j F Y’);
?>[/php]

  • You can either use the double quotes (“”) or single quotes (‘’) to display string.



  • You can even add “comments” to your code.


“Comment” – It is basically a piece of free text that can be shown an where in the script and is completely ignored by PHP.

Different “comment” styles supported by PHP are :-

1.      Single line comment (i.e. “/……/” or  “#” )

2.      Multi-line comment  (i.e. “/*………….*/”).

 Creating your first script:

  • In order to create and run your PHP scripts you will have to install PHP, MySQL, Apache.If you do not have PHP and other stuffs installed follow this link here which has a complete package of all the software’s you need.


http://www.wampserver.com/en/download.php

Note:- WAMP is Windows Apache MySQL PHP. Where the initial “W” determinesthe platform compatibility. Similarly there are LAMP, MAMP , and XAMPP.

“X” is compatible on all platforms i.e. LINUX, MAC, WINDOWS.I assume that most of them are using WINDOWS platform here.

The installation includes :-

- Apache 2.2.17

 - Php 5.3.3

 - Mysql 5.1.53 (version 64 bits)

 - Mysql 5.5.8 (version 32 bits)

 - PhpMyadmin 3.2.0.1

 - SQLBuddy 1.3.2

  • After installing WAMP, a new directory will be created in your “C:” drive which will contain a folder “www


Note:- when ever you create a PHP file you should save it in c:wampwww”.


  • To run any PHP file first start the “WAMP” server by double clicking on  the icon created on your desktop.



  • After the server is online i.e. “ON” next thing to do is to open your web browser and type in


http://localhost/time.php

Alright we have now completed Lesson 1 (Part 1).Hope you like this tutorial. You have now learnt how  PHP works on a web environment and what a simple PHP script looks like. We will discuss about variables in the next Lesson. You can download the files for practice that I have included in the Download.

PHP Tutorial Part 2


download

Jul 10, 2011

Wordpress Make HTML5 theme

HTML 5 is the latest and the hottest topic in the web development.
Now a days everybody wants there blogs theme to be in HTML5, even the latest WP-3.2 default theme twenty eleven is also in HTML-5.

So why to wait, convert our current blog old html theme to brand new HTML-5

In this tutorial, you are going to learn the conversion of old HTML to HTML-5

1. Basic Document’s structure

[php]
<!doctype html>
<head>
</head>
<body>
<header>
</header>
<section id="content">
<article>
<header>
</header>
</article>
</section>
<aside>
<nav>
</nav>
</aside>
<footer>
</footer>
</body>
</html>
[/php]

As we can see, that the tags are very new to us. If we add following CSS:
article, aside, figure, footer, header, hgroup, menu, nav, section { display:block; }
we are free to format them like other block elements, e.g.


  • Tag Header, as the name itself indicates that all the head contents like, logo, navigation, search etc will come into it. The usage of this tag inside
    will be presented below.



  • tag used to keep the order in document. We can divide the website into sections, e.g. content, comments, gallery etc.



  • can be used to store our entries – each entry in separate tag! The title and meta of entry should be inside
    – it will have positive impact on our SEO.



  • Our sidebar should be inside






  • If we have footer it is a good practice to put it inside
    . We can have more than one
    , but each should be inside separate
    and one can be directly inside


Tags  like article, header, footer, section can be used more than one time, but the structure has to be maintained.

[php]
<section id="content">
<article>
<header>
</header>
<p>
</p>
<footer>
</footer>
</article>
</section>
[/php]

In header, we can put h3 tag, which is commonly used in wordpress themes content.
If you want to use more then one time hx tags, then it should be wrapped inside hgroup tag.

[php]
<hgroup>
<h3>Main Title</h3>
<h4>Subtitle</h4>
</hgroup>
[/php]

The meta of the post can be wrapped by
, what is a convenient solution.


When it comes to the comments we can treat them like posts and put inside
with >header>,


,
etc. inside.


When we want to refresh our comment form we should definitely use HTML5. Some new input features have been added. Let’s take a look on this:

[php]
<input type="text" name="author" id="comment-form-author" placeholder="Your name" value="" size="22" tabindex="1" required="required">

<input type="email" name="email" id="comment-form-email" placeholder="Your email" pattern="[^ @]*@[^ @]*" value="" size="22" tabindex="2" required="required">

<input type="text" name="url" id="comment-form-url" placeholder="Your website" size="22" tabindex="3" />
[/php]

As a value of placeholder we can specify a hint for user, it will appear as a text inside the input and after clicking on it will disappear.
pattern attribute allows us to specify a patter than must be followed. Here we have an example of pattern for email address.

HTML5 is powerful tool, but it’s not completely supported by all browsers.
More cool features we can find on http://html5demos.com/