Showing posts with label html5. Show all posts
Showing posts with label html5. Show all posts

Friday, March 29, 2013

Graph Colouring

       Now, I am creating a web application, Graph Coloring.The graphs are drowned using nodes and lines. In this Graph Coloring application, the nodes of the graph are colored using different colors for adjacent nodes. My application has two parts, one python script that runs in server and the other, an html file which act as user interface for the users.The html file provides the graphical view representation of my application.This application will be explained in detail, later on.

Graph and Graph Coloring

        Mathematically, a graph is a representation of a set of objects where some pairs of the objects are connected by links. The interconnected objects are represented by mathematical abstractions called vertices, and the links that connect some pairs of vertices are called edges.Vertices are also called nodes or points, and edges are also called lines or arcs.
        In Graph theory, graph coloring is a special case of graph labeling. In its simplest form, it is a way of coloring the vertices of a graph such that no two adjacent vertices share the same color; this is called a vertex coloring.

        Now let's going through the codes.In my application, i have used canvas in html file.Canvas is a rectangular portion or area within the html page, and you can control every pixel in it. The canvas element has several methods for drawing paths, boxes, circles, characters, and adding images. For drawing within the canvas, you should need Javascript. The codes are below.
<canvas id="graph" width="700" height="440" style="border:2px solid #000000;"></canvas>
The above code is used for drawing a canvas in html5. I have choose JavaScript for drawing on canvas.More details on canvas and Javascript are available at: http://www.w3schools.com/html5/html5_canvas.asp. 

       Here in the graph application my aim is use javascript for detecting the mouse movements so that i can get the position of each mouse click. Thus getting the points where mouse is clicked, so that i can draw the vertex and lines. I have assigned different clicks for application, double click for creating a node and two single clicks for drawing a line. My codes for mouse actions are below.

function Point(x,y){
    this.x = x;
    this.y = y;
}

function getMousePos(e){
    var point = new Point(0,0);
    if (e.pageX != undefined && e.pageY != undefined) {
point.x = e.pageX;
point.y = e.pageY;
}
    else{
point.x = e.clientX + document.body.scrollLeft +
document.documentElement.scrollLeft;
point.y = e.clientY + document.body.scrollTop +
document.documentElement.scrollTop;
}

    point.x -= canvas.offsetLeft;
    point.y -= canvas.offsetTop;
    return point;      
}

In the above code, mouse points are returned.the vertex and line are drowned using this points.

function drawcircle(e){
    point=getMousePos(e);
    if(checkNode(point,40)==-1){
Vertex(point,"black");
context.font = "10pt Courier New";
context.fillText(v,point.x+10,point.y-20);
v++;
vertex_list.push(point);
}
    else{ 
        alert("node overlapped");
}
}

function drawline(e){
    var point = getMousePos(e);
    var vertex_no=checkNode(point,40);
    if(vertex_no>=0){
if(start_edge==0){
 start_edge=1;
 selected_vertex=vertex_no;
 context.beginPath();
       context.moveTo(vertex_list[vertex_no].x, vertex_list[vertex_no].y);
}
else{
 start_edge=0;
          if(adj_list[selected_vertex]==undefined)
adj_list[selected_vertex]= new Array();
 if(adj_list[vertex_no]==undefined)
adj_list[vertex_no]= new Array();
 if(selected_vertex!=vertex_no){
adj_list[selected_vertex].push(vertex_no);
adj_list[vertex_no].push(selected_vertex);
 }
 context.lineTo(vertex_list[vertex_no].x,vertex_list[vertex_no].y)
 context.stroke();
 context.closePath(); 
}
}
    else
start_edge=0;
    }

       The functions ‘drawline’ and ‘drawcircle’ gets called when the user clicks, i.e. double or single click, anywhere within the canvas. Its arguments is a MouseEvent object that contains information about where the user clicked. Each functions calls getMousePos(e), where the getMousePos(e) returns the values of mouse coordinates where ever the user clicks within the canvas. The values are returned to a vertex_list.After the values are returned, they are used to draw nodes and lines within the canvas.
       Now for the coloring part, an adjacency list containing the list of nodes is needed for coloring.Since the html file is the client and the adjacency list are sent to the server. For communicating with server, i.e. the python script, jQuery is used.i have used jQuery for sending the adjacent list to the server running the python script where the coloring algorithm is implemented.For more details on jQuery visit http://www.w3schools.com/jquery/default.asp.
The complete the code of Graph coloring application is available at: https://github.com/jaseemkp/Graph-Coloring-Django
You can try the graph coloring application at : http://jastech-graph.herokuapp.com/

Wednesday, March 20, 2013

Paint Application Using Flask and Sqlite3


     Now, I have rewritten the paint application in Google AppEngine using Flask framework.The html frontend and javascript are same.Please refer my earlier post about paint application for more info.Instead of google datastore, sqlite3 was used for data storage.I will explain how to connect to database and retrive data from it.


def connect_db():
    return sqlite3.connect('paint.db')

@app.before_request

def before_request():
    g.db = connect_db()
    g.db.execute("CREATE TABLE IF NOT EXISTS drawings(fname string primary key, img_data text)")
@app.after_request
def after_request(response):
    g.db.close()
    return response

First we define a function 'connect_db()' for connecting to database before requesting.Then create a table in database file(paint.db) for storing fname and img_data.


@app.route('/', methods=['GET', 'POST'])
def paint():
    if request.method == 'GET':
        py_all = {}
        all_data = g.db.execute("SELECT * FROM drawings")
        for data in all_data:
            py_all[data[0]] = data[1]
        return render_template('paint.html', py_all= py_all)
    elif request.method == 'POST':
        filename = request.form['fname']
        data = request.form['whole_data']
        g.db.execute("REPLACE INTO drawings(fname, img_data) VALUES (?, ?)", (filename, data));
        g.db.commit()
        return redirect('/')

          In GET method the data executed from database is render to  paint.html file.The data taken from data base is stored in 'py_all' object.When user tries to save the image, server gets a POST request.  the image name and its data are saved into a table using the sqlite3 module available in python. Sqlite3 is a basic database interface available in python.
The code can be found Here

Friday, March 15, 2013

Paint App using javascript and html5

      This is my basic paint application using Javascript and HTML5. This web application consist of tools to draw rectangle and circle with ten colors. HTML5 canvas is used for making the drawing space.Two canvases are used to draw shapes, the real canvas is used to store the shapes and temporary canvas is used for drawing shapes in temporarily . The color picker is made using the table method in html.The application works basically on three mouse events onmousedown, onmouseup and onmousemove.To see it in action Click on the Paint Application Figure :

      The script start drawing once the mousedown and mousemove event occurs and continue until the mousedown event occurs. The method used to draw rectangle and circle are different. For example, to draw a rectangle we need to know the left top coordinate plus the length and breadth of the rectangle.arc method is used to draw circles on canvas. The application also provide the facility to clear the canvas if anything drowned in it. Tools are selects using current_tool function in script.The function Draw is used to Drawing shapes like rectangle or circle in canvas.When we draw a shape, the values of shapes are pushed to Object(named data).

Paint with saving facility:
       This application also provides the facility to save our drawings.This is done by saving values about each object needed to regenerate the same drawing. for example, for a rectangle it would be the type of the object which is "rectangle", its beginning coordinates and end coordinates are saved to regenerate the rectangle.All the shapes are saved in same manner.Different functions are used to Drawing and regenerating same our drawings When we click the save button the data is transferred to the server as a json string where it is stored along with a name provided by the user . Since we have a save feature it is quite easy to implement the edit feature also.Just regenerate the drawing using the data received from the server,make some changes and save it with the same name or a new name ,as the user wishes. JSON is syntax for storing and exchanging text information.
The complete code is available Here.To see it in action Click Here