• Shortcuts : 'n' next unread feed - 'p' previous unread feed • Styles : 1 2

» Publishers, Monetize your RSS feeds with FeedShow:  More infos  (Show/Hide Ads)


Date: Wednesday, 12 Dec 2012 16:43

After several months of invite only access, the Node.js hosting platform Modulus has opened its doors to everyone.

Modulus is a full-featured Node.js platform service that provides support for WebSockets, custom domains, custom SSL, integrated MongoDB, and powerful statistics and metrics.

Registration and application hosting are completely free during the public beta, so this is the perfect time to jump on and test drive this new product.

Author: "The Reddest" Tags: "Tech News, Node.js"
Comments Send by mail Print  Save  Delicious 
Date: Thursday, 06 Dec 2012 17:05

Basic authentication can be a quick and efficient way to protect your content. Combined with SSL it’s also very secure. This article describes how to add basic authentication to a Node.js Express application.

Express App

The first thing we need is an Express application. Creating an Express app is extremely simple, and the makers of Express do a pretty good job documenting the process.

package.json

{
  "name" : "BasicAuthExample",
  "version" : "0.0.1",
  "dependencies" : {
    "express" : "3.x"
  }
}

app.js

var express = require('express');
var app = express();

app.get('/home', function(req, res) {
 res.send('Hello World');
});

app.listen(process.env.PORT || 8080);

The application has one route defined, /home. Right now there is no authentication. Anyone can access /home and see the content. If you host the application on Modulus the PORT environment variable will be defined, otherwise I’m simply using 8080.

Global Authentication

The first technique we’ll see is adding authentication globally to every route. Fortunately with Express, we can do this with a single line.

Synchronous

This technique is the simplest, but least flexible. The authentication will occur synchronously with hard-coded values.

var express = require('express');
var app = express();

// Authenticator
app.use(express.basicAuth(‘testUser’, 'testPass'));

app.get('/home', function(req, res) {
 res.send('Hello World');
});

app.listen(process.env.PORT || 8080);

In this example, to access any route in our application the user must enter the username, ‘testUser’, and the password, ‘testPass’.

Synchronous Function

The second technique is also synchronous, but provides a little more flexibility. This time we’re going to define a function that simply has to return true or false.

var express = require('express');
var app = express();

// Authenticator
app.use(express.basicAuth(function(user, pass) {
 return user === 'testUser' && pass === 'testPass';
}));

app.get('/home', function(req, res) {
 res.send('Hello World');
});

app.listen(process.env.PORT || 8080);

As you can see, we now pass a function as the authentication mechanism instead of the username and password. The function gets as arguments the username and password specified by the user. Technically you don’t even need to use these as part of the authentication, since all you have to do is return true or false.

Asynchronous

The last technique is the most flexible. With an async callback you could lookup the username and password in a database.

var express = require('express');
var app = express();

// Authenticator
app.use(express.basicAuth(function(user, pass, callback) {
 var result = (user === 'testUser' && pass === 'testPass');
 callback(null /* error */, result);
}));

app.get('/home', function(req, res) {
 res.send('Hello World');
});

app.listen(process.env.PORT || 8080);

This example also takes a function, but instead of only passing the username and password, it also passes a callback function that should be invoked with the result. The callback utilizes the error-first pattern, so the first parameter should be null if no errors occurred. The second parameter to the callback is the result (true or false) of the authentication.

Single-Route Authentication

The above three techniques can also be used to secure individual routes. Just like before we define our authentication handler, except this time we need to save it to a variable.

// Synchronous
var auth = express.basicAuth('testUser', 'testPass');

// Synchronous Function
var auth = express.basicAuth(function(user, pass) {
 return user === 'testUser' && pass === 'testPass';
});

// Asynchronous
var auth = express.basicAuth(function(user, pass, callback) {
 var result = (user === 'testUser' && pass === 'testPass');
 callback(null /* error */, result);
});

All that we have to do now is pass the authenticator to the routes we’d like protected.

app.get('/home', auth, function(req, res) {
 res.send('Hello World');
});

app.get('/noAuth', function(req, res) {
 res.send('Hello World - No Authentication');
});

As you can see, the /home route still requires authentication since we’ve passed the authenticator as the second parameter. The /noAuth route is publically available since an authenticator was not supplied.

And there you have it. We’ve seen all the ways to add basic authentication to your Node.js Express application. If you’ve got any questions or comments leave them in the comments below.

This article is re-posted from the Modulus Blog with permission from the original authors.

Original source: Node.js and Express - Basic Authentication

Author: "The Reddest" Tags: "Tutorials, Node.js, Javascript"
Comments Send by mail Print  Save  Delicious 
Date: Thursday, 25 Oct 2012 16:06

Isaac Schlueter, the author of NPM (npmjs.org) and the lead maintainer of Node.js is answering questions for the next few days on the open Q&A platform Crowdhall.

If you've got any questions about Node.js or Isaac's personal life, now's your change to ask him any question you'd like.

Author: "The Reddest" Tags: "Neat Websites"
Comments Send by mail Print  Save  Delicious 
Date: Wednesday, 17 Oct 2012 20:44

One of the best use cases for Node.js is real-time applications that handle lots of small requests simultaneously. A perfect example of this is a small chat application that allows multiple users to connect and send messages to each other. So today we are going to build this.

Simple Chat
Check out the live version.

We are going to be utilizing a technology called WebSockets, which will allow us to easily communicate between all of the users of our application. We are utilizing WebSockets via a Node module called Socket.IO. However, before we can dig into all the communications we are going to need some Node code.

For static content, we are using Express. May be a little overkill, but it does the job. The base app.js file will look like so:

var express = require('express');
var app = express();
var server = require('http').createServer(app);

server.listen(80);

app.use("/", express.static(__dirname + '/public'));

Nothing special. What we need now though is some Socket.IO action. We need to accept an incoming message then blast it out to everyone else that is listening to our server. Thankfully it is a small tweak on the server-side:

var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);

server.listen(80);

app.use("/", express.static(__dirname + '/public'));

io.sockets.on('connection', function (socket) {
  socket.on('msg', function (data) {
    io.sockets.emit('new', data);
  });
});

Yeap, a require statement and two callbacks later we have our server-side code. Basically what this is doing is waiting for a connection, then when a connection is established it subscribes to the "msg" event that happens when a client sends a message to the server. When this happens, we send the message to all connected clients, or "sockets" as they are called in this case. Simple stuff.

The client is a bit more complicated though. Let's start with the HTML, which is pretty straight-forward.

<!DOCTYPE HTML>
<html>
  <head>
    <title>Simple Chat</title>
    <script type="text/javascript" src="/socket.io/socket.io.js"></script>
    <script
     type="text/javascript"
     src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js">
    </script>
  </head>
  <body>
    <div id="wrapper">
      <h1>Simple Chat</h1>
      <div id="messages"></div>
      <div class="nic">
        Your Name
        <input id="name" name="name" type="text"/>
      </div>
      <textarea id="message"></textarea>
      <input id="send" type="submit" value="Send"/>
    </div>
  </body>
</html>

The important bit here is the inclusion of /socket.io/socket.io.js. This is the client-side piece of socket.io, and will provide us with a simple way to communicate with our server. The coolest part is that the socket.io Node module sets up this route for us on the server, so we don't have to do anything server-side to get this route to work.

To organize our chat code, we are going to create a JavaScript module which will provide a single, global instance to utilize. To start, let's just get the module code:

//Create a chat module to use.
(function () {
  window.Chat = {
  };
}());

This will create a single instance of the Chat object in the global scope. However, we are going to need our Chat object to do something. Initialization is always pretty important, so we can add that next.

//Create a chat module to use.
(function () {
  window.Chat = {
    socket : null,
 
    initialize : function(socketURL) {
      this.socket = io.connect(socketURL);

      //Send message on button click or enter
      $('#send').click(function() {
        Chat.send();
      });

      $('#message').keyup(function(evt) {
        if ((evt.keyCode || evt.which) == 13) {
          Chat.send();
          return false;
        }
      });

      //Process any incoming messages
      this.socket.on('new', this.add);
    }
  };
}());

In the initialize method, we are setting up the socket.io connection, subscribing to the new event, and making sure the send button and enter key do something productive. There is just one problem here, we don't have an add function for the socket.on call to use. Let's add that.

//Create a chat module to use.
(function () {
  window.Chat = {
    socket : null,
 
    initialize : function(socketURL) {
      this.socket = io.connect(socketURL);

      //Send message on button click or enter
      $('#send').click(function() {
        Chat.send();
      });

      $('#message').keyup(function(evt) {
        if ((evt.keyCode || evt.which) == 13) {
          Chat.send();
          return false;
        }
      });

      //Process any incoming messages
      this.socket.on('new', this.add);
    },

    //Adds a new message to the chat.
    add : function(data) {
      var name = data.name || 'anonymous';
      var msg = $('<div class="msg"></div>')
        .append('<span class="name">' + name + '</span>: ')
        .append('<span class="text">' + data.msg + '</span>');

      $('#messages')
        .append(msg)
        .animate({scrollTop: $('#messages').prop('scrollHeight')}, 0);
    }
  };
}());

Take some message data and add it to the DOM, that's all we are doing here. Nothing special.

The final piece to this puzzle is actually sending the data.

//Create a chat module to use.
(function () {
  window.Chat = {
    socket : null,
 
    initialize : function(socketURL) {
      this.socket = io.connect(socketURL);

      //Send message on button click or enter
      $('#send').click(function() {
        Chat.send();
      });

      $('#message').keyup(function(evt) {
        if ((evt.keyCode || evt.which) == 13) {
          Chat.send();
          return false;
        }
      });

      //Process any incoming messages
      this.socket.on('new', this.add);
    },

    //Adds a new message to the chat.
    add : function(data) {
      var name = data.name || 'anonymous';
      var msg = $('<div class="msg"></div>')
        .append('<span class="name">' + name + '</span>: ')
        .append('<span class="text">' + data.msg + '</span>');

      $('#messages')
        .append(msg)
        .animate({scrollTop: $('#messages').prop('scrollHeight')}, 0);
    },

    //Sends a message to the server,
    //then clears it from the textarea
    send : function() {
      this.socket.emit('msg', {
        name: $('#name').val(),
        msg: $('#message').val()
      });

      $('#message').val('');
    }
  };
}());

With socket.io you do two things: listen to events and trigger events. You listen with on (as we have seen), and you trigger events with the emit method. So when a message is ready to be sent, all we have to do is "emit" it with the message data. It will then be picked up on the server and emit it back out to all the sockets connected.

The only thing left to do is include it in the HTML and initialize it.

<!DOCTYPE HTML>
<html>
  <head>
    <title>Simple Chat</title>
    <script type="text/javascript" src="/socket.io/socket.io.js"></script>
    <script
     type="text/javascript"
     src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js">
    </script>
    <script type="text/javascript" src="chat.js"></script>
  </head>
  <body>
    <div id="wrapper">
      <h1>Simple Chat</h1>
      <div id="messages"></div>
      <div class="nic">
        Your Name
        <input id="name" name="name" type="text"/>
      </div>
      <textarea id="message"></textarea>
      <input id="send" type="submit" value="Send"/>
    </div>
    <script type="text/javascript">
      $(document).ready(function() {
        Chat.initialize('http://localhost/');
      });
    </script>
  </body>
</html>

There it is, a complete chat application. If you run the Node script, it will start up and let you know socket.io is ready. Then you can bring up localhost and start chatting with...well, yourself if you run it locally. I have included all the code in a ZIP (or you can get it from github), as well as the addition of a little bit of "style" so it looks a little better. Don't forget to npm install!

Hopefully this has been an informative, quick introduction to using WebSockets in Node.js. Just remember, when you need coding help, all you have to do is Switch On The Code.

Attached Media: application/zip ( 2 ko)
Author: "The Hairiest" Tags: "Tutorials, JSON, Node.js, Javascript"
Comments Send by mail Print  Save  Delicious 
Date: Tuesday, 18 Sep 2012 14:47

Today we are making a simple puzzle game called "Fifteen". The purpose of the game is to slide 15 square blocks around to form an image. The goal of this tutorial is to look at this simple browser-based game and explain how it was made line by line. It's a great way to learn jQuery!

For this tutorial, we will use a 2D image square-sliding game, which I will go over line by line to demonstrate the train of thought behind the code.

A jQuery plugin is a perfect way to create image slideshows, custom user interface controls and of course browser-based games. We won't just write JavaScript code here, we will create a jQuery plugin.

A plugin is nothing more than our own custom jQuery method. You know how we have jQuery's methods .css() and .animate()? Well, jQuery gives us the ability to extend its own functionality with custom methods that we create ourselves. Like the existing jQuery methods, we can apply the method we will create to a jQuery selector.

Well, the game is called Fifteen, and we want to make our game "embeddable" inside an arbitrary HTML element like <div id = "target">here</div> so we can move it around anywhere on the page (Different sites have different layouts, wouldn't you like to have the ability to embed your jQuery game/plugin into an arbitrary DIV element on any site?)

Let's get started with the jQuery code.

We will actually create our own jQuery method and call it .fifteen(). Therefore, in order to launch the game inside an HTML element with the id "target" we will call this command:

$("#target").fifteen(128);

This will create and attach the game board to the div whose id is "target." Also, each square will become 128 by 128 pixels in width and height based on the only passed parameter.

Executing a custom method as shown in the code above will pass the selector string "#target" to our plugin function which grabs the DIV. Inside our custom method, we can refer to that selector/element using the this keyword. And we can also enable jQuery methods on it by passing it to the new jQuery object like so:

$(this);

In order to create our own jQuery plugin we will use the $.fn.extend() method.

We can also refer to this as extending functionality of the jQuery library with our own methods

Let's take a look:

$.fn.extend({
  fifteen: function (square_size) {
    // Game code goes here...

    // Example -- set the width of all\
    // DIVs to what was passed as square_size
    $("div").css({width: square_size});

    // The basics of the inner-workings of a plugin:
    // refers to the passed selector,
    // eg: $("#target")
    // same thing, but with jQuery methods enabled
    var a = this;                      
    var b = $(this);            

    // Let's do something with the HTML
    // element passed as the CSS selector
    // paint all text inside "#target" red
    this.style.color = "red";
    // same exact thing, using jQuery method .css()  
    $(this).css("color", "red");
  }
});

That's it! This is the basic structure of any jQuery plugin.

The code examples I use above are just examples that show how the basics work internally. But we will write an entire game within the scope of the function we called "fifteen".

Within the scope of the plugin the this object refers to what was passed in the selector. Also, the square_size parameter is just a custom, arbitrary parameter passed to our game.

We decide what the parameters should be, and if your game or plugin require more, simply define more parameters, as in:

$.fn.extend({
  fifteen: function(square_size, param2, param3, etc) {
    /*.. game code...*/
  }
});

Within the scope of your plugin you refer to parameters by the very same names.

In our case square_size is the only parameter. It defines the arbitrary size of the square in the game. I use 128 (as in 128 pixels in width and height). The grid is 16 by 16, but there are only 15 movable squares, because one is always empty. However, we still create all 16 DIVs, and just make one white. We do this in order to simulate the shadow effect on an empty square.

Before we get into the code, let's take a look at the game's construction as far as HTML goes. You will notice that there are 16 squares and each square is a separate DIV element:

The Fifteen Game in Action

Well hello there...

You can see the game in action here.

The point of the game is to shuffle the image, one square at a time (by shifting it into the empty square, thus swapping locations) until the image is complete.

The white square is always empty. You are only allowed to shift squares that can physically be shifted into the empty spot, as if on a physical game board. This means only squares to the north, south, west and east of the empty square can be shifted. This test is performed within the stand-alone function I wrote and called Move() - it is separate from the plugin itself, it's like a helper function.

Before we dive into the code, we need to briefly talk about some common problems we will face while designing a plugin-based game.

Embedding the Plugin Into Arbitrary DIVs (or other HTML elements)

Remember that when writing your plug-in it is wise to inject the HTML elements which are created as part of the game... into a parent DIV. The purpose of this is that your plug-in becomes embeddable into any arbitrary HTML element. Different websites have different layouts. So it's important for our plug-in to be flexible. That it could be embedded into an arbitrary HTML element anywhere on the page. In this example I called that element:

<DIV id = "target"></DIV>

Moving around this element will physically move the game around anywhere on the page.

Injecting HTML into Empty Elements Using the .append(html) Method

We leave the div unpopulated, without any game HTML. Why's that? This is because the plugin itself will generate the game's HTML elements and insert them into the target DIV. No need to pre-type them "by hand."

This is smart, because it keeps the parent element clean. But also, this example in particular allows us to explore the jQuery's native .append(html) method. It literally appends new HTML at the end of a specified element. That is, you never even have to write HTML into the document itself, the .append() method injects HTML into the web page dynamically, you just specify the target element using a selector like:

// Add one div to the end of #board
$("#board").append("<div></div>");

Using :nth-child(index) Instead of IDs or Classes

I think it's worth mentioning that we can refer to DIVs inside, say, a parent DIV as children. This is really helpful. For example, let's say we have 16 DIVs (children) stored inside one parent DIV:

<div id = "board"> <!-- This is called a "parent" element //-->
  <div></div>
  <div></div>
  <div></div>
  <!-- ... ok, imagine 16 DIVs here. These are the "children" of "#board" //-->
  <div></div>
  <div></div>
</div>

You don't really need to assign 16 IDs to all 16 DIVs! jQuery takes care of that for us. For example, to refer to the 3rd DIV inside a parent DIV (in our game it's #board,) instead, we can do something like this without ever assigning any classes or ids to any of the children:

// Hide 3rd DIV in the list of children.
//No need to assign an id to each one!
$("#board").children("div:nth-child(3)").hide();

Notice we used the .children() method to grab all children of a parent (DIVs inside parent,) and then we also specified that we need a 3rd child using the literal selector :nth-child(n) where n is the index of the DIV we need. Note, however that this index doesn't start with 0 like JavaScript arrays. It starts with index of 1. :nth-child(0) will not select anything.

The Code

Well, I think we are ready to start writing the code. Let's get to it.

// This is a JavaScript event.
// It means - once DOM is finished loading,
// execute everything inside the callback function scope
// This is where we initialize the game
$(document).ready(function()
{
  // Initialize the game and create the plugin

  // When the squares swap places, the moving square must always appear on top
  var zi = 1; // We increment z-index each time a square is shifted

  // The index of the empty square by default, the 16th square
  var EmptySquare = 16;

  // Now, this is where we create the plugin and call it fifteen.
  $.fn.extend({
    fifteen: function(square_size) {
      // Grab the id of the HTML element into which we are placing the game,
      // it is the selector - "#target" from  $("#target").fifteen(128);
      var targetElement = "#" + $(this).attr("id");

      var sqSize = square_size + 'px';
      var boardSize = (square_size * 4) + 'px';

      // Inject DIV into target, this is our game board
      $(targetElement).html(
        "<div id = 'board'></div>"
      );

      $("#board").css({
        position:'absolute',
        width: boardSize,
        height: boardSize,
        border: '1px solid gray'
      });

      // Populate the game board's HTML container with 15 squares
      for (var i = 0; i < 16; i++)
      {
        // A  dirty way to create an arbitrary DIV and
        // append it into HTML dynamically
        // Notice each square uses the same image monalisa.jpg
        // It just uses a different x/y offset for each square
        $("#board").append(
          "<div style='" +
            "position: absolute;" +
            "left: " + ((i % 4) * square_size) + "px;" +
            "top: " + Math.floor(i / 4) * square_size + "px;" +
            "width: " + square_size + "px;" +
            "height: " + square_size + "px;" +
            "text-align: center;" +
            "line-height: 128px;" +
            "-moz-box-shadow: inset 0 0 20px #555555;" +
            "-webkit-box-shadow: inset 0 0 20px #555555;" +
            "box-shadow: inset 0 0 20px #555555;" +
            "background: #ffffff url(monalisa.png) " +
              (-(i % 4) * square_size) + "px "
              + -Math.floor(i / 4) * square_size + "px " +
              "no-repeat !important'>" +
        "</div>");
      }

      // Empty up the 16th square, as the starting point
      // EmptySquare = 16
      $("#board")
        .children("div:nth-child(" + EmptySquare + ")")
        .css({
          backgroundImage: "",
          background: "#ffffff"
        });

      // Attach click event to each square
      $("#board").children("div").click(function() {
        Move(this, square_size);
      });
    }
  });

  // Move() is the function that is called when a square is clicked
  // Note that it is independent of the plugin itself which is described above
  // It takes two parameters,
  //     1. object handle to the square that was clicked, and
  //     2. the width of the square
  function Move(clicked_square, square_size)
  {
    // We need to locate movable tiles based on where the empty spot is,
    // We can only move the four surrounding squares
    var movable = false;

    // Swap x/y between the clicked square and the currently empty square
    var oldx = $("#board")
      .children("div:nth-child(" + EmptySquare + ")")
      .css("left");
   
    var oldy = $("#board")
      .children("div:nth-child(" + EmptySquare + ")")
      .css("top");

    var newx = $(clicked_square).css("left");
    var newy = $(clicked_square).css("top");

    // The clicked square is north of the empty square
    if (oldx == newx && newy == (parseInt(oldy) - square_size) + 'px') {
      movable = true;
    }

    // The clicked square is south of the empty square
    if (oldx == newx && newy == (parseInt(oldy) + square_size) + 'px') {
      movable = true;
    }
       
    // The clicked square is west of the empty square
    if ((parseInt(oldx) - square_size) + 'px' == newx && newy == oldy) {
      movable = true;
    }
       
    // The clicked square is east of the empty square
    if ((parseInt(oldx) + square_size) + 'px' == newx && newy == oldy) {
      movable = true;
    }
   
    if (movable)
    {
      // Increment zindex so the new tile is always on top of all others
      $(clicked_square).css("z-index", zi++);

      // Swap squares... Animate new square into old square position
      $(clicked_square).animate({ left: oldx, top: oldy }, 200, function()
      {
        //Move old square into new square position
        $("#board")
          .children("div:nth-child(" + EmptySquare + ")")
          .css("left", newx);
       
        $("#board")
          .children("div:nth-child(" + EmptySquare + ")")
          .css("top", newy);
      });
    }
  }

  // Ok, we're ready to initialize the game, let's do it.
  // Create a game with 128 by 128 squares inside "#target" div:
  $("#target").fifteen(128);
});

With the page looking like:

<html>
  <body>
    <!-- This is where the game will be injected //-->
    <div id = "target"></div>
  </body>
</html>

I tried to explain the code to the best of my ability here but some details were skipped because there is so much more to JavaScript.

If you feel like you still need to understand what some of the things mean I recommend grabbing a copy of my jquery tutorial book which contains a multitude of tutorials and visual diagrams. They are designed to help you build your understanding of JavaScript and jQuery so you can write your own plugins, games, etc.

I hope you enjoyed this tutorial and perhaps learned a thing or two.

Author: "gregsidelnikov" Tags: "Tutorials, jQuery, Javascript"
Comments Send by mail Print  Save  Delicious 
Date: Monday, 10 Sep 2012 02:58

If you're using Express and Node.js to create an API, it's likely you'll want all of the responses to be of a single type, probably JSON. This is easily accomplished by adding a few routes that catch every request, set the content type, and then calling next() to pass the request to the next handler.

// GET
app.get('/*', function(req, res, next) {
  res.contentType('application/json');
  next();
});

// POST
app.post('/*', function(req, res, next) {
  res.contentType('application/json');
  next();
});

// PUT
app.put('/*', function(req, res, next) {
  res.contentType('application/json');
  next();
});

// DELETE
app.delete('/*', function(req, res, next) {
  res.contentType('application/json');
  next();
});

Since Express evaluates routes in the order they are added, these will have to be defined before the more specific ones. In this example, every request made to the application will first be caught by these handlers and then passed on using the next() function.

Another way to accomplish this is by providing some custom middleware. The use function defines a function that will be called in the process of completing a request. This will need to be executed before the routes are defined.

app.use(function(req, res, next) {
  res.contentType('application/json');
  next();
});

In this example, every request that comes into Express will pass through this function. We have to the ability to do whatever we want with it before continuing. In this case, setting the content type.

Author: "The Reddest" Tags: "Snippet Tutorials, Node.js, Javascript"
Comments Send by mail Print  Save  Delicious 
Date: Thursday, 23 Aug 2012 14:52

Here's the problem: How do I check the version of node from inside the running app? Fortunately, the answer is easy. Node's global process object has a version property that contains all the info you'll need.

console.log(process.version);

// v0.8.5

Author: "The Reddest" Tags: "Snippet Tutorials, Node.js, Javascript"
Comments Send by mail Print  Save  Delicious 
Date: Monday, 13 Aug 2012 13:10

Node.js is growing like crazy, and with that popularity comes companies offering platforms to host those applications. The ecosystem is still young, but below is a list of the companies I've found that offer a home for your Node.js projects.

Nodejitsu

http://nodejitsu.com

Nodejitsu is currently the leading name in the Node.js platform service provider space. Their PAAS offering is lightweight, but functional. One neat feature they offer is the ability to rollback to previous versions of your application.

Status: Public
Deploy: Web, CLI
Scaling: Multiple Drones


Modulus

http://modulus.io

Modulus is new to the Node.js PAAS space and focuses heavily on providing metrics surrounding your application and its performance. They also provide integrated disk access that's shared across all instances of your app.

Status: Public Beta
Deploy: Web, CLI
Scaling: Multiple Servos


Cloudnode

http://cloudno.de

Cloudnode is built on top of Nodester's open-source stack. They offer integrated access to CouchDB and Redis.

Status: Private Beta
Deploy: Git
Scaling: Not yet


Nodester

http://nodester.com

Nodester's entire infrastructure is open source. Almost all interactions with the service will be done through the CLI and their hosting offering is extremely lightweight.

Status: Private Beta
Deploy: Git
Scaling: Not yet


Nodesocket

http://nodesocket.com

Node.js apps in Nodesocket are run inside dedicated VMs. Control over your apps are done entirely through a REST service.

Status: Discontinued
Deploy: Git, SFTP
Scaling: None


Appfog

http://appfog.com

Appfog takes a very different approach to provisioning resources for your applications. Customers allocate a global amount of memory and then fit as many instances as they can by adjusting the amount of memory per instance. They've been for around, started with PHP, and have recently added Node.js.

Status: Public
Deploy: CLI
Scaling: Multiple Instances


Heroku

http://heroku.com

If you're looking into PAAS, you've heard of Heroku. They made their name by hosting Rails apps and have recently expanded to several other platforms.

Status: Public
Deploy: Git
Scaling: Multiple Dynos


Azure Websites

http://windowsazure.com

Microsoft has been expanding quickly into the IAAS and PAAS spaces. Azure Websites is their PAAS offering and supports Node.js as well as other frameworks.

Status: Public Beta
Deploy: Git, TFS, FTP
Scaling: Multiple instances


This is the list I could find through my normal searching, but I know there are more. If I missed any, drop them in a comment so we can all check them out.

Author: "The Reddest" Tags: "Neat Websites"
Comments Send by mail Print  Save  Delicious 
Date: Monday, 06 Aug 2012 15:57

Are you a Node.js developer with callbacks that are getting out of hand? Maybe you are a JavaScript developer who wants to learn more about Node? Or maybe you are just looking to meet other developers for beer and pizza? Whatever the case, you need to come down to The Brandery for the first ever Node.Cincy meetup.

Sponsored by Modulus, Jetpacks for Dinosaurs (providing some books to give away), and The Brandery, Node.Cincy will be a collection of developers getting together to learn and talk about all things Node.js. If you are any sort of web developer, this is the meetup for you.

Head over to the meetup to find out more, and we hope to see you there!

When: August 8th, 7:00PM

Where: The Brandery

1411 Vine Street
Cincinnati, OH 45202
Goto Google Maps

What: Node user group, free beer and pizza

Author: "The Hairiest" Tags: "Tech News"
Comments Send by mail Print  Save  Delicious 
Date: Tuesday, 10 Jul 2012 23:01

More than likely your Node.js application is acting like some sort of web service. Every once in a while your web service needs to communicate with another one. In this tutorial I'm going to demonstrate how to invoke an HTTP request using Node.js and post some JSON data to it.

My assumption for this article is that you've already got a Node.js application up and running, so I'm going to skip most of the boilerplate code and get right to the important stuff. The first thing we'll need is some data to post, which you've probably already got, but here's mine.

var user = {
  username: 'The Reddest',
  email: 'brandon@switchonthecode.com',
  firstName: 'Brandon',
  lastName: 'Cannaday'
};

You can post data in several ways, but the most common and what we're going to use is string data. Fortunately it's super simple to convert an object into a string using the built-in JSON class.

var user = {
  username: 'The Reddest',
  email: 'brandon@switchonthecode.com',
  firstName: 'Brandon',
  lastName: 'Cannaday'
};

var userString = JSON.stringify(user);

Now we need to tell the remote server what kind of data we're sending, in the form of headers.

var user = {
  username: 'The Reddest',
  email: 'brandon@switchonthecode.com',
  firstName: 'Brandon',
  lastName: 'Cannaday'
};

var userString = JSON.stringify(user);

var headers = {
  'Content-Type': 'application/json',
  'Content-Length': userString.length
};

The "Content-Type" header tells the remote server we're going to be sending a JSON string. The "Content-Length" is just the number of characters we're sending. If you're sending files, this field will be how large the file is, in bytes.

Next up we need to specify what server we want to talk to and how we're going to do it. This is done using a simple options object. This object will be supplied to Node.js when we make the actual request.

var user = {
  username: 'The Reddest',
  email: 'brandon@switchonthecode.com',
  firstName: 'Brandon',
  lastName: 'Cannaday'
};

var userString = JSON.stringify(user);

var headers = {
  'Content-Type': 'application/json',
  'Content-Length': userString.length
};

var options = {
  host: 'myServer.example.com',
  port: 80,
  path: '/user/TheReddest',
  method: 'POST',
  headers: headers
};

In my example I'm going to post data to myServer.example.com:80/User/TheReddest. Notice that there is no leading 'http://' in front of the host - DO NOT add a leading 'http://' to the host.

Now it's time to make the actual request. Fortunately Node.js makes this pretty easy.

var http = require('http');

...

// Setup the request.  The options parameter is
// the object we defined above.
var req = http.request(options, function(res) {

});

So far, we haven't actually done anything. We still need to write our data to the request and read the response. Let's start with writing our data.

var http = require('http');

...

// Setup the request.  The options parameter is
// the object we defined above.
var req = http.request(options, function(res) {

});

req.write(userString);
req.end();

At this point, the remote server will received your posted data. All that's left is to read the response. This is done inside the callback that's supplied to the http.request function.

var http = require('http');

...

// Setup the request.  The options parameter is
// the object we defined above.
var req = http.request(options, function(res) {
  res.setEncoding('utf-8');

  var responseString = '';

  res.on('data', function(data) {
    responseString += data;
  });

  res.on('end', function() {
    var resultObject = JSON.parse(responseString);
  });
});

req.write(userString);
req.end();

The response that comes back from the remote server can appear in multiple chunks. This means the 'data' callback may be invoked multiple times. The responses do come back in order, so all we have to do is append all the responses together into a single string. The 'end' callback will be invoked when everything has been received. The remote server you're connecting to may or may not return JSON, but in my example it does, so I simply use JSON.parse to convert it into a usable object.

The last thing you'll probably want to do is handle errors. This is done by simply hooking the 'error' event on the request object.

var http = require('http');

...

// Setup the request.  The options parameter is
// the object we defined above.
var req = http.request(options, function(res) {
  res.setEncoding('utf-8');

  var responseString = '';

  res.on('data', function(data) {
    responseString += data;
  });

  res.on('end', function() {
    var resultObject = JSON.parse(responseString);
  });
});

req.on('error', function(e) {
  // TODO: handle error.
});

req.write(userString);
req.end();

Just for good measure, here's all the code in one piece:

var http = require('http');

var user = {
  username: 'The Reddest',
  email: 'brandon@switchonthecode.com',
  firstName: 'Brandon',
  lastName: 'Cannaday'
};

var userString = JSON.stringify(user);

var headers = {
  'Content-Type': 'application/json',
  'Content-Length': userString.length
};

var options = {
  host: 'myServer.example.com',
  port: 80,
  path: '/user/TheReddest',
  method: 'POST',
  headers: headers
};

// Setup the request.  The options parameter is
// the object we defined above.
var req = http.request(options, function(res) {
  res.setEncoding('utf-8');

  var responseString = '';

  res.on('data', function(data) {
    responseString += data;
  });

  res.on('end', function() {
    var resultObject = JSON.parse(responseString);
  });
});

req.on('error', function(e) {
  // TODO: handle error.
});

req.write(userString);
req.end();

And there you have it. This tutorial demonstrates how to POST JSON data to a remote server using Node.js. If you have any questions or comments feel free to leave them below.

Author: "The Reddest" Tags: "Tutorials, Node.js, Javascript"
Comments Send by mail Print  Save  Delicious 
Date: Thursday, 19 Apr 2012 15:31

If you've ever built a client/server application, you know how tedious it can be get access to a working server in order to test client functionality. With the right design, however, this is a headache we don't have to experience. This approach was used by our team recently when developing the Facebook game, Tic-Tac-Together, and proved to be quite successful.

The root of this design involves encapsulating the communication layer into separate objects, which you should be doing anyway. Putting communication logic directly in your higher-level code is just asking for future maintenance difficulties. For Tic-Tac-Together (TTT) we needed two communication objects: one for our server and one for the Facebook API. Below is a snippet of each class with the implementations removed.

//
// Server Class
//
ttt.Server = function() {

};

// Connects to the server.
ttt.Server.prototype.connect = function(url, callback) {
  // All the logic required to connect to the TTT server.
};

// Gets a user based on their facebook ID.
ttt.Server.prototype.getUser(facebookId, callback) {
  // Sends a get user request to the server.
};

//
// Facebook class
//
ttt.Facebook = function() {

};

// Initializes the facebook interface.
ttt.Facebook.prototype.init = function(apiKey) {
  // Initialize the Facebook JS SDK.
};

Normally I'd write all of the implementation here and then wait around for a server to become available to test if anything worked. What we're going to do instead is create two copies of each class with the exact same signature. The live version will do real communications, and the fake version will do whatever we need it to for local testing.

//
// Test Server Class
//
ttt.test.Server = function() {

};

// Connects to the server.
ttt.test.Server.prototype.connect = function(url, callback) {
  // Don't actually need to do anything, just raise the callback.
  if(callback) {
    callback();
  }
};

// Gets a user based on their facebook ID.
ttt.test.Server.prototype.getUser(facebookId, callback) {
  var user = new ttt.model.User();
  user.name = "Test User";
  user.id = 1;

  if(callback) {
    callback(user);
  }
};

//
// Test Facebook class
//
ttt.test.Facebook = function() {

};

// Initializes the facebook interface.
ttt.test.Facebook.prototype.init = function(apiKey) {
  // Don't actually need to do anything here.
};

The only difference between the signatures is that I put the two new classes in another namespace, test. As you can see, the test versions of these classes don't do any actual server communication. When connecting to the server, the client is immediately notified by raising the callback. When initializing the Facebook API, the test code doesn't even have to do anything. When requesting a user, the test class generates a user and immediately returns it to the calling code. This is a very powerful aspect of this design - when testing locally I can change the data being returned from the test objects to whatever I need in order to fully exercise the client code.

Since the live and test versions share the same signatures, code that calls them does not have to know which version is being used. When you want to toggle between local testing and live testing, simply construct the appropriate version of the class.

var server = new ttt.test.Server();  // Test version.
//var server = new ttt.Server();  // Live version.

var facebook = new ttt.test.Facebook(); // Test version.
// var facebook = new ttt.Facebook(); // Live version.

facebook.init();

server.connect(function() {
  alert('connected');
});

server.getUser(10, function(user) {
  alert('name: ' + user.name);
});

As seen above, the server and facebook variables can either be the live version or the test version. The code beneath their initialization doesn't care at all.

Having to maintain two versions of the same class has proved to be irritating, but the benefits are well worth it. If you're using a classical inheritance scheme, like John Resig's, you could create base classes for each communication object and extend them for the live and test versions. That approach has benefits and leads to a more flexible design - you could easily add multiple test objects and override individual functions for different behavior.

There are lots of possible variations on this design, but what you should remember is the core idea. When designing your system, include the ability to run your client code without requiring a live (and properly functioning) server. If you have any questions, feel free to drop them below. If you're waiting for your code to compile, you should also challenge someone to a friendly game of Tic-Tac-Together.

Author: "The Reddest" Tags: "Tutorials, Javascript"
Comments Send by mail Print  Save  Delicious 
Date: Thursday, 22 Mar 2012 17:17

We all love jQuery. Its a simple fact that it provides powerful tools to get your JavaScript done right. However, one of its most powerful features is its extensiblity, and many developers have taken full advantage of this. This has created plenty of plugins to choose from, and today we are going to look at some of our favorite ones to hit the scene.

#10: jQuery UI

Site | Demo

This is one of the most extensive and flexible JavaScript UI frameworks out there. jQuery UI offers up everything from simple yet fancy buttons to complete accordions and autocompletes. It also has a pretty simple and powerful dialog framework that makes popups a snap. However, the best part about the whole deal is that you can create your very own theme right on the website, to fit your style, complete with custom-colored images and all.

Quick Snippet:
<div id="dialog" title="Basic dialog">
  <p>This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p>
</div>
$( "#dialog" ).dialog();


#9: Roundabout

Site | Demo

Sliders are not only one of the most popular ways to fancy up a dull site, but they can be quite a tedious pain to implement. There are plenty of options to choose from when it comes to plugins in this area, but the Roundabout is one of the best. It offers a neat style and is quite easy to get up and get running. It's also flexible enough to morph into other uses, such as animations or a neat way to pick form values. Quick Snippet:
<ul id="myRoundabout">
  <li><span>Block 1</span></li>
  <li><span>Block 2</span></li>
  <li><span>Block 3</span></li>
  <li><span>Block 4</span></li>
  <li><span>Block 5</span></li>
</ul>
$('ul#myRoundabout').roundabout();


#8: Slides

Site | Demo

While Roundabout offers a neat, new-age way to rotate through summary-type content, sometimes you need something a bit less fancy. This is where slides comes in. It will give you an easy option for "sliding" between content, but is open enough to give you control over the things you want, such as style and transitions. To top it all off, it gives you paging right out of the box, which is always nice to have for sliders. Quick Snippet:
<div id="slides">
  <div class="slides_container">
    <div>
      <h1>Slide 1</h1>
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
    </div>
    <div>
      <h1>Slide 2</h1>
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
    </div>
    <div>
      <h1>Slide 3</h1>
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
    </div>
    <div>
      <h1>Slide 4</h1>
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
    </div>
  </div>
</div>
$("#slides").slides();


#7: Simple Modal

Site | Demo

One thing that makes Simple Modal attractive is its name sake...its simplicity. Its lightweight and requires very little setup to get going. Some modals out there require a lot of elements to be on the page or complicated style setup, but not Simple Modal. However, like any self-respecting plugin, all of the setup is exposed, so if you really want to go overboard with styles and just animations, you can. Quick Snippet:
$.modal("<div><h1>SimpleModal</h1></div>");


#6: qTip2

Site | Demo

When you need tooltips and mouseovers to be exactly what you want, in the position that you want, the style that you want, qTip2 is your unequivocal answer. It offers not only a comprehensive list of options, but comes with some pretty snazzy styles right out of the box. You can also load all kinds of content inside your tooltips as well, from simple text or images to AJAX retrieved data. If you include qTip2 in your jQuery project, you will probably never need another solution for useful tooltip feedback. Quick Snippet:
$('a[title]').qtip();


#5: jquery.cookie

Github

Despite the chocolate-chipy goodness we all want to think about right now, web cookies are still an important part of our developer lives. Pretty much any modern website uses them in some capacity. Luckily, using jQuery and the jquery.cookie plugin, accessing them via JavaScript is a breeze. A great example of a simple, effective solution. Quick Snippet:
$.cookie('the_cookie', 'the_value');
$.cookie('the_cookie'); // => 'the_value'


#4: ColorBox

Site | Demo

Lightbox is an extremely powerful popup library for displaying and organizing media, with a lot of different offshoots to choose from. ColorBox is one of the offshoots. The difference is that it is designed to not only be lightweight and work with jQuery, but it is also extremely easy to customize it to the looks you want. Some of these types of plugins can be very complex, but luckily you have ColorBox on your side to simplify things up for you. Quick Snippet:
<a class="group1" href="../content/ohoopee1.jpg" title="Me and my grandfather on the Ohoopee.">Grouped Photo 1</a>
<a class="group1" href="../content/ohoopee2.jpg" title="On the Ohoopee as a child">Grouped Photo 2</a>
<a class="group1" href="../content/ohoopee3.jpg" title="On the Ohoopee as an adult">Grouped Photo 3</a>
$(".group1").colorbox({rel:'group1'});


#3: jQuery Mouse Wheel

Github

In straight JavaScript, handling the mouse wheel event can be tricky at best. To make things worst, jQuery does not have native support for getting the mouse wheel event. This is where the mouse wheel plugin comes in. It literally just adds a bindable event to jQuery so you can hook into the mouse wheel scroll event, for all your wheel scrolling pleasure. Quick Snippet:
$('#my_elem').bind('mousewheel', function(event, delta, deltaX, deltaY) {
    console.log(delta, deltaX, deltaY);
});


#2: jQuery Validation

Site | Demo

Validation is one of those necessary things that can require a lot of time. From creating complex regular expressions, to styling things to make errors obvious to the user, it can be quite a task. With all this in mind, it is quite amazing when you see how much of this can be accomplished with jQuery Validation, with a very minimal effort. It even hooks in some custom selectors to help you keep track of all your validated elements. You are not going to find a more comprehensive validation solution for jQuery, hands down. Quick Snippet:
<form id="commentForm" method="get" action="">
    <fieldset>
    <p>
      <label for="cname">Name (required, at least 2 characters)</label>
      <input id="cname" name="name" class="required" minlength="2" />
    </p>
    <p>
      <label for="cemail">E-Mail (required)</label>
      <input id="cemail" type="email" name="email" class="required" />
    </p>
    <input class="submit" type="submit" value="Submit"/>
  </fieldset>
</form>
$("#commentForm").validate();


#1: Tablesorter

Site | Demo

Most solutions for handling tables and the data therein are server/client-side meshes that provide a good way to show and organize data. The only issue with that is speed, which can suffer if you have such a complex solution. Tablesorter helps to aliviate some of this issue by, well, helping you sort your tables on the client-side. It can sort a lot of options for sorting all kinds of data, and has a pleasingly simple design. A great addition to any data-driven interface. Quick Snippet:
<table cellspacing="1" class="tablesorter">            
  <thead>
    <tr>
        <th>first name</th>
        <th>last name</th>
        <th>age</th>
        <th>total</th>
        <th>discount</th>
        <th>date</th>
    </tr>
  </thead>
    <tbody>
    <tr>
      <td>peter</td>
      <td>parker</td>
      <td>28</td>
      <td>$9.99</td>
      <td>20%</td>
      <td>jul 6, 2006 8:14 am</td>
    </tr>
    <tr>
      <td>john</td>
      <td>hood</td>
      <td>33</td>
      <td>$19.99</td>
      <td>25%</td>
      <td>dec 10, 2002 5:14 am</td>
    </tr>  
  </tbody>
</table>
$("table").tablesorter();


So there you have it. Ten awesome jQuery plugins that will help you in just about any situation you may find yourself in. That is the beauty of something as robust as jQuery, you can always find an easy to use and quick to implement solution for the problem at hand.

So this wraps it up for now. Just remember, if you need coding help, all you have to do is Switch On The Code.

Author: "The Hairiest" Tags: "Neat Software, jQuery, Javascript"
Comments Send by mail Print  Save  Delicious 
Date: Monday, 12 Mar 2012 19:04

We've been hard at work and the effort has paid off. As of today, Pulse is ready for the mainstream. We've open-sourced the project and we've chosen the MIT license, which gives devs a lot of flexibility in how they use the framework.

There's still a lot of work that needs to get done, like making the website better, more supporting documentation, and definitely some example games, but none of that is needed for you to download and begin using Pulse.

Even though it's released, we're nowhere near done with it. We've got an endless backlog of awesome features that we're dying to add, and Pulse will only get better as we continue to improve it.

As you use the framework, we want to hear what you think. Even if it's the most minor feature request or question, we don't care, drop us a line.


Author: "The Reddest" Tags: "Tech News"
Comments Send by mail Print  Save  Delicious 
Date: Friday, 09 Mar 2012 15:07

In a previous tutorial we showed you how to dynamically add and remove rows from a table. This is a very useful technique, but sometimes you might need to add entire bits of HTML into a table as just a string. In this situation, things can get a little tricky.

Let's say you have a table, and you need to insert HTML into it. Either you have a AJAX call that returns a string of HTML, or you just like slapping HTML into a table. Sometimes that's just what you have to do. In the tutorial mentioned above, DOM methods were used to insert rows. While this is the preferred and suggested method, from time to time you end up with this situation:

var html = '<tr><td>Some Data</td></tr>';
var table = document.getElementById('myTable');

table.innerHTML += html;

Now, this may seem like the perfect way to do things, but there are several problems. First off, most browsers require and even add a tbody tag. So right off the bat we are selecting the wrong element to add our HTML to.

However, that isn't the biggest problem we will run into. In Internet Explorer, innerHTML is read only on tables. Yeap, read only. Since we all like to be cross-browser compatible, the solution above is unacceptable.

At this point, using jQuery would be a good option, as it would allow you to convert an HTML string into something you can append to the table. At the very least it provides more enhanced tools for dealing with tables, as well having hoards of plugins for this exact kind of task.

That being said, all you will be doing with jQuery is converting the string into usable DOM objects, and if you absolutely have to do it with plan ol' javascript, it is possible (of course). It actually only takes a few simple lines of Javascript:

var html = '<tr><td>Some Data</td></tr>';
var table = document.getElementById('myTable').getElementsByTagName('tbody')[0];
var tmpTable = document.createElement('div');
tmpTable.innerHTML = '<table><tbody>' + html + '</tbody></table>';
var tr = tmpTable.getElementsByTagName('tr')[0].cloneNode(true);
table.appendChild(tr);

Basically what we are doing is creating a temporary table to convert our string into usable DOM objects. We do this by setting the innerHTML of div (which we create), which allows use to then get our original table row as a DOM object. From there it's as easy as appending it to our table body.

So there you have it, converting a string to DOM objects for use in a table. That wraps it up for this tutorial. Just remember, when you need coding help all you have to do is Switch On The Code.


Author: "The Hairiest" Tags: "Snippet Tutorials, Javascript"
Comments Send by mail Print  Save  Delicious 
Date: Tuesday, 21 Feb 2012 15:15

While working on the Pulse graphics engine I'm learning all kinds of new techniques and tid bits about Canvas. One of the latest things I've been playing around with and working on is creating shadows. This is actually pretty easy with the JavaScript drawing api available for canvas. It actually just takes a few properties set on the canvas context.

Before jumping into the code there are a couple of items to note. First, you can selectively apply a shadow by using the save and restore methods on the context. Second, for performance reasons make sure to draw shadows as infrequently as you can. Now let's jump into the code.

function bodyloaded() { // Attached to body's onload event

  var canvas = document.getElementById('myCanvas'); // Grabs the canvas element
  var ctx = canvas.getContext('2d'); // Grabs the canvas context

  ctx.save(); // Save the state of the context
  ctx.fillStyle = '#4433FC'; // Sets the fill color
  ctx.shadowOffsetX = 2; // Sets the shadow offset x, positive number is right
  ctx.shadowOffsetY = 2; // Sets the shadow offset y, positive number is down
  ctx.shadowBlur = 4; // Sets the shadow blur size
  ctx.shadowColor = 'rgba(0, 0, 0, 0.6)'; // Sets the shadow color
  ctx.beginPath(); // Starts a shape path
  ctx.arc(150, 150, 75, 0, 2 * Math.PI, false); // Draws a circle
  ctx.fill(); // Fills the path
  ctx.restore(); // Restore the state of the context

  ctx.fillStyle = '#DE33FC'; // Sets the fill color
  ctx.beginPath(); // Starts a shape path
  ctx.arc(350, 350, 60, 0, 2 * Math.PI, false); // Draws a circle
  ctx.fill(); // Fills the path
}

That'll spit out something like the following.

Looking at the code it starts out by grabbing the canvas and then the context from the canvas. In order to apply the drop shadow to only a part of the canvas we have to use the save and restore functions on the context. The next thing done is to set the appropriate properties on the canvas context.

  • shadowOffsetX - the horizontal offset for the drop shadow
  • shadowOffsetY - the vertical offset for the drop shadow
  • shadowBlur - the size of the blur of the drop shadow
  • shadowColor - the color of the drop shadow

At a minimum the shadowBlur and shadowColor properties have to be set in order for the shadow to be used. The color can be set with any of the formats available for fill style or stroke color. I'd recommend using the 'rgba' format so you can set the alpha on the color.

That wraps it up for this tutorial. Make sure to check out some of other canvas tutorials here on the site. If you have any questions or comments, feel free to leave them below.

If you're looking for more information on HTML5 Canvas. Check out these great books:


Author: "The Fattest" Tags: "Tutorials, HTML, Javascript"
Comments Send by mail Print  Save  Delicious 
Date: Wednesday, 15 Feb 2012 22:47

Namespaces can be a powerful tool for code organization and conflict avoidance. Unfortunately, Javascript does not have native support for this extremely useful construct. That being said, the language's flexibility allows us to create a facsimile that works quite well.

Namespace Declaration

We're going to use objects to simulate namespaces. At the top of each file where you want to include and use a namespace, add the following line.

var myNamespace = myNamespace || {};

This line will either create a new object to hold our namespace or return the existing one. Technically this line only needs to be added to the top of the first script file included on the page, but it's much easier (and better for testing) to just add it to every file.

Usage

Now that we have an instance of an empty object, all we have to do is add objects to it.

var myNamespace = myNamespace || {};

// Declare a new object.
myNamespace.MyObject = function() {
  this.myProperty = "someValue";
};

// Create an instance of the object.
var myInstance = new myNamespace.MyObject();

console.log(myInstance.myProperty); // someValue

As you can see, by assigning a function (class) to the property myNamespace.MyObject, we've essentially simulated adding an object to a namespace. Any number of objects can be added to our namespace like this, and since MyObject is now inside myNamespace, we don't have worry about conflicting with all the other Javascript that might be running on the page.

And there you have it - an extremely simple solution to namespacing your Javascript code. It's probably a good idea to use namespaces whenever possible since you never know whether or not a type already exists that you're about to redefine. If you're building a public library, like jQuery, then it should be an absolute requirement.

Want to learn more about Javascript? Check out these great books:


Author: "The Reddest" Tags: "Tutorials, Javascript"
Comments Send by mail Print  Save  Delicious 
Date: Tuesday, 14 Feb 2012 15:36

Over the past few months, we have talked quite a bit about HTML5, more specifically canvases. There are plenty of other interesting HTML5 subjects canvases offer, which makes it by far the most fascinating and flexible object. We have covered topics ranging from simple rotations to photo filters. Today we are going to go over how to take your canvas and save it as an image.

Below we have a working demonstration of the concept this tutorial will cover. If you click "Image Tag", a new image element will be inserted into the contents of this page. The image element will be populated by the contents of the canvas. If you click "New Window", the contents of the canvas will be displayed as an image in a new browser window or tab. If you click "Download", the browser will prompt you to download the contents of the canvas as an image file.

Introduction

Getting the pixel data from a canvas is fairly simple, as we learned in the grayscale filter tutorial. Luckily, getting "image ready" data is also extremely easy as well.

Before we get started with some code, it should be noted that you can only get image data, in any form, from sources on the same domain on the canvas. This means that, while you can draw cross-domain images, you cannot get pixel data nor image data from canvases that have cross-domain images drawn on them.

Digging In

Now, the code to get your image data is actually really straight forward. All you have to do is have some fun with a canvas, then get a data string and us it accordingly. So here is what our code looks like:

var can = document.getElementById('canvas');
var ctx = can.getContext('2d');

var imgA = new Image();
imgA.src = 'vader.jpg';

imgA.onload = function() {
  ctx.drawImage(imgA, -25, 0, imgA.width, imgA.height);
  ctx.restore();
};

var imgB = new Image();
imgB.src = 'troopers.jpg';

imgB.onload = function() {
  ctx.globalAlpha = 0.1
  ctx.drawImage(imgB, -100, -75, imgB.width, imgB.height);
  ctx.restore();
};

function toImage(returnType) {
  var dataURL = document.getElementById('canvas').toDataURL("image/png");

  // The returnType argument specifies how to get the
  // the image.  'obj' will set the source to an image element.
  // 'window' will open a new window and display the image.
  // 'download' will prompt the user to save the image.
  switch(returnType) {
    case 'obj':
      var imgObj = new Image();
      imgObj.src = dataURL;
      document.getElementById('graphics').appendChild(imgObj);
      break;
    case 'window':
      window.open(dataURL, "Canvas Image");
      break;
    case 'download':
      dataURL = dataURL.replace("image/png", "image/octet-stream");
      document.location.href = dataURL;
      break;
  }
}

In our example, we take two images and layer them, with the on top image mostly transparent, to give us a trendy fade-in look.

So first thing we do is take two images and draw them to a canvas, with one being drawn on top of the other with 50% opacity. However, what you put on your fancy canvas is up to you, the important part is getting that data into an image.

The magic revolves around the call to toDataURL inside our toImage function, which actually returns a string that contains the image data (in URL form) for the canvas. Also notice that this call is on the canvas itself and not the 2d context we use to draw the images.

Once you have this string, you can use it many different ways. You can make an image and set the source to the data, open the data in a new window, or even point the location of the current document to the data which allows you to do a straight-up download of the image. All these methods offer a way to get the canvas data as an image, we have them all inside our function. All three methods have been included so you can see how they are each accomplished. Again, very simple code.

So there you have it. Saving canvas data as an image is quite easy, and you can present that data in any number of ways...as long as you don't use cross-domain images. This is going to wrap it up for this tutorial, just remember when you need coding help, all you have to do is Switch On The Code.

Want to learn more about Canvas? Check out these great books:


Attached Media: application/x-javascript ( 1 ko)
Author: "The Hairiest" Tags: "Tutorials, HTML, Javascript"
Comments Send by mail Print  Save  Delicious 
Date: Thursday, 02 Feb 2012 15:26

HTML 5 and the Canvas tag has brought a whole world of possibilities when it comes to image manipulation. This tutorial will demonstrate one of those possibilities that is particularly powerful - getting raw image data and transforming it.

We've done a conversion to grayscale tutorial before using C# and this tutorial will look fairly similar to an approach outlined in that article.

Grayscale Example

There actually isn't too much code, so I'm going to just throw the entire contents here and explain what's going on after.

// Create an image object.     
var image = new Image();

// Can't do anything until the image loads.
// Hook its onload event before setting the src property.
image.onload = function() {

   // Create a canvas.
   var canvas = document.createElement('canvas');
   
   // Get the drawing context.
   var ctx = canvas.getContext('2d');
   
   // Get the width/height of the image and set
   // the canvas to the same size.
   var width = image.width;
   var height = image.height;
   
   canvas.width = width;
   canvas.height = height;
   
   // Draw the image to the canvas.
   ctx.drawImage(image, 0, 0);
   
   // Get the image data from the canvas, which now
   // contains the contents of the image.
   var imageData = ctx.getImageData(0, 0, width, height);
   
   // The actual RGBA values are stored in the data property.
   var pixelData = imageData.data;
   
   // 4 bytes per pixels - RGBA
   var bytesPerPixel = 4;
   
   // Loop through every pixel - this could be slow for huge images.
   for(var y = 0; y < height; y++) {
      for(var x = 0; x < width; x++) {
         // Get the index of the first byte of the pixel.
         var startIdx = (y * bytesPerPixel * width) + (x * bytesPerPixel);
         
         // Get the RGB values.
         var red = pixelData[startIdx];
         var green = pixelData[startIdx + 1];
         var blue = pixelData[startIdx + 2];
         
         // Convert to grayscale.  An explanation of the ratios
         // can be found here: http://en.wikipedia.org/wiki/Grayscale
         var grayScale = (red * 0.3) + (green * 0.59) + (blue * .11);  
         
         // Set each RGB value to the same grayscale value.
         pixelData[startIdx] = grayScale;
         pixelData[startIdx + 1] = grayScale;
         pixelData[startIdx + 2] = grayScale;
      }
   }
   
   // Draw the converted image data back to the canvas.
   ctx.putImageData(imageData, 0, 0);
};

// Load an image to convert.
image.src = "myImage.png";

The first thing we need is an image to convert. There are multiple ways to get image objects, but this is one of the easiest. I hook the image's onload event and then set the source to a URL. It's important to note here that you can't convert images that aren't hosted on the same domain - the canvas is said to be tainted by a cross domain image and therefore getImageData and putImageData no longer work.

Since we can't get information directly from an image, we have to draw it to a canvas first. I simply create a canvas the same size as the image and paint the image to it.

The conversion process is actually pretty simple. We just need to loop through every pixel, convert it to grayscale, and draw the new image back to the canvas. The conversion equation, (red * 0.3) + (green * 0.59) + (blue * 0.11), does a better job than just taking the average of the three values. You can read a little bit more about those values on Wikipedia's Grayscale page.

After we've converted every pixel, we just call putImageData to draw the converted image back to the canvas. And that's all there is to it - you now have a black and white version of your picture.

This is a pretty basic example of using an image's raw data, but you can begin to see the power developers now have. If you've got any questions, feel free to leave them below.

Want to learn more about the HTML 5 Canvas? Check out these great books:


Author: "The Reddest" Tags: "Tutorials, Javascript"
Comments Send by mail Print  Save  Delicious 
Date: Tuesday, 31 Jan 2012 16:21

Displaying a message box in an iPhone application is something I have to look up almost every time. I decided it was time to create a tutorial on the subject - then maybe I'd actually remember the syntax. This tutorial will be short, but should cover pretty much everything you'd need to know in order to show alerts in an iPhone application.

If you want to display a simple notification, the syntax is actually pretty short.

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"My Title"
                                                message:@"My Message"
                                               delegate:nil
                                      cancelButtonTitle:@"OK"
                                      otherButtonTitles:nil];

[alert show];

That will give you a message box that looks like this:

UIAlertView Example

Unlike a lot of other UI frameworks, the show function does not block until the alert is dismissed - execution will continue immediately. In order to know what button was pressed we're going to have to specify a delegate object. In the above example, you'll see the delegate argument is nil. Alternatively, we could provide an object that will act as a receiver for various actions.

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"My Title"
                                                message:@"My Message"
                                               delegate:self
                                      cancelButtonTitle:@"OK"
                   otherButtonTitles:@"Button 1", @"Button 2", @"Button 3", nil];

// otherButtonTitles is a comma delimited list of strings, terminated with a nil.

[alert show];

...


// This function will be called by the UIAlertView.
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
  // The cancel button ("OK") is always index 0.
  // The index of the other buttons is the order they're defined.
}

The UIAlertViewDelegate has lots of helpful callbacks that can be used to determine how a user is interacting with your message box. The example above is probably one of the most common - determining which button was pressed when the view is dismissed. The cancel button is always index 0. The index of the other buttons will start at 1 and then increment in the order they're defined ("Button 1" = 1, "Button 2" = 2, etc).

That code gives us something that looks like this:

UIAlertView with multiple buttons

And I think that finishes up this tutorial. There's not much to the UIAlertView, and I hope this tutorial at least points you in the direction of all the things it offers. If you've got any questions, feel free to drop them below.

Want to learn more about iPhone programming? Check out these great books:




Author: "The Reddest" Tags: "Snippet Tutorials, Objective-C, Cocoa To..."
Comments Send by mail Print  Save  Delicious 
Date: Friday, 27 Jan 2012 15:25

One interesting corner of HTML5 development is web-based games. With a few well placed canvases and a healthy does of Javascript, you can create just about any game you can dream. However, the complex nature of Javascript has created the need for a few companies to release game engines built entirely in Javascript and HTML5. This is where Pulse comes in.

Pulse is a game engine built in Javascript. It utilizes HTML5 canvases to display and animate various elements and offers features like event handling, audio, and sprite sheet animations. With the recent release of the developer preview, I would like to take a few minutes and go over some of the neat features that Pulse has to offer.

Lets's start with a simple sample. Note that all our game-specific code is bundled in the mygame.js file.

<html lang="en">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Paddle Game</title>
    <script src="pulse.js" type="text/javascript"></script>
    <script src="mygame.js" type="text/javascript"></script>
  </head>
  <body>
    <div style="width: 760px; height: 480px;" id="gameWindow"></div>
  </body>
</html>

Pulse comes as a single Javascript file and including it is as easy as adding a reference to that file. Now that Pulse is included, let's take a look at our myGame.js Javascript file.

// Hook the ready event.  This will fire
// when the DOM and Pulse are both ready for use
pulse.ready(function() {

  // Create the engine, scene, and layer.
  var engine = new pulse.Engine({ gameWindow: 'gameWindow', width: 760, height: 480 });
  var scene = new pulse.Scene();
  var layer = new pulse.Layer();
 
  // Create a Score object.  The Score class extends pulse.CanvasLabel.
  var score = new Score( { text: "0 | 0" } );
  score.position.x = 300;
  score.position.y = 200;
 
  // Create a ball, position it, and set a few properties.
  var ball = new Ball({ src: 'ball.png', size: {width: 16, height: 16} });
  ball.position.x = 300;
  ball.position.y = 200;
  ball.velocity.x = .25;
  ball.velocity.y = .25;
  ball.score = score;
  layer.addNode(ball);
 
  //Create the paddles and position them.
  var paddle = new Paddle({ src: 'paddle.png' });
  paddle.ball = ball;
  paddle.position.x = 20;
  paddle.position.y = 150;
 
  var aiPaddle = new Paddle( { src: 'paddle.png' });
  aiPaddle.ball = ball;
  aiPaddle.position.x = 730;
  aiPaddle.position.y = 150;
  aiPaddle.auto = true;
 
  // Add the paddles and the score object to the layer.
  layer.addNode(paddle);
  layer.addNode(aiPaddle);
  layer.addNode(score);
 
  // Make the layer's origin 0,0. The origin defines how objects
  // are positioned - by default objects are positioned by their centers.
  // (0,0) represents the top-left corner.
  layer.anchor.x = 0;
  layer.anchor.y = 0;
 
  // Add the layer to the scene, then add the scene to the engine.
  scene.addLayer(layer);
  engine.scenes.addScene(scene);

  // Activate the scene.
  engine.scenes.activateScene(scene);
 
  // Start the game loop and provide a callback, loop,
  // that will be invoked on each update loop.
  engine.go(20, loop);
});

This example is the start of a pong game, with a few things stripped out for simplicity. All the basic Pulse elements are there though. You create some game objects, in this case paddles and a ball, then add them to a layer. This layer then gets added to a scene. Finally the scene is added to the game.

Once all the objects, layers, and scenes are setup, you just create a main logic loop (which is empty here), then call engine.go(). All of this is wrapped in a ready call so the game is started when the browser is finished loading Pulse and the rest of the website.

Most engines follow this paradigm, but Pulse makes it extremely easy. With a few lines, you can have game objects loaded and update logic running. You just have to set up a few layers and a scene or two, and you are good to go. However, ease of use is not the only strong point of Pulse.

One of the more advanced features Pulse has is a very structured object hierarchy, all built to be extensible. Any, and I do mean any, Pulse object can be extended and added to. Not only is it possible to extend an object, it is extremely easy. In the example above the Paddle, Ball, and even the Score object are actually extensions of a base Pulse object. Here are the classes in full, take a look:

var Paddle = pulse.Sprite.extend({
  init: function(params) {
   
    // Call the base constructor.
    this._super(params);
   
    // Add properties to determine what arrow key has been pressed.
    this.arrowUp = false;
    this.arrowDown = false;
   
    this.size.width = 50;
    this.size.height = 200;
   
    // Bind the key events to set the arrow up/down properties.
    this.events.bind('keydown',
      function(e) {
        if(e.keyCode == 38) {
          e.sender.arrowUp = true;
        }  
        else if(e.keyCode == 40) {
          e.sender.arrowDown = true;
        }
      });
     
    this.events.bind('keyup',
      function(e) {
        if(e.keyCode == 38) {
          e.sender.arrowUp = false;
        }  
        else if(e.keyCode == 40) {
          e.sender.arrowDown = false;
        }
      });
  },
 
  /* The update function runs every game "tick." This update function
     will move the paddle based on what key is currently down, as long
     as it is in the bounds of the game canvas. */

  update: function(elapsed) {
    this._super(elapsed);
   
    if(this.auto) {
      if(this.ball.position.y < this.position.y) {
        this.position.y -= .15 * elapsed;
      }
      else if(this.ball.position.y > this.position.y) {
        this.position.y += .15 * elapsed;
      }
    }
    else {
      if(this.arrowUp) {
        this.position.y -= .15 * elapsed;
      }
      else if(this.arrowDown) {
        this.position.y += .15 * elapsed;
      }
    }
  }  
});

var Ball = pulse.Sprite.extend({
 
  init: function(params) {
   
    // Call the base constructor.
    this._super(params);
   
    // Setup a few velocities, which determine the ball's speed.
    this.velocity = { };
    this.velocity.x = .25;
    this.velocity.y = .25;
   
    // The bounds of the area in which the ball can go.
    this.maxX = 760;
    this.maxY = 480;
  },
 
  /* Bounces the ball if it has made it to any of the bounds,
     at a 45 degree angle. Also increments the score if it has
     reached a horizontal bounds, IE has made it to a players side. */

  update: function(elapsed) {
    this._super(elapsed);
   
    this.position.x += elapsed * this.velocity.x;
    this.position.y += elapsed * this.velocity.y;
   
    var xMax = this.maxX - (this.size.width / 2);
    var yMax = this.maxY - (this.size.height / 2);
    var xMin = this.size.width / 2;
    var yMin = this.size.height / 2;
   
    if(this.position.x > xMax) {
      this.position.x = xMax;
      this.velocity.x *= -1;
      this.score.playerScore();
    }
   
    if(this.position.x < xMin) {
      this.position.x = xMin;
      this.velocity.x *= -1;
      this.score.aiScore();
    }
   
    if(this.position.y < yMin) {
      this.position.y = yMin;
      this.velocity.y *= -1;
    }
   
    if(this.position.y > yMax) {
      this.position.y = yMax;
      this.velocity.y *= -1;
    }
  },
});

// This class keeps track of the score and draws it to the canvas.
var Score = pulse.CanvasLabel.extend({
  init: function(params) {
    this._super(params);
   
    this.scoreA = 0;
    this.scoreB = 0;
  },
 
  playerScore : function() {
    this.scoreA++;
    this.text = this.scoreA + " | " + this.scoreB;
  },
 
  aiScore : function() {
    this.scoreB++;
    this.text = this.scoreA + " | " + this.scoreB;
  }
});

As you can see, all that it takes is a simple call to the extend method one any object and you have the ability to make your own subclass. In this case we are just overriding the update function, but the possibilities are endless.

Put all this together and you get a simple pong game that looks like so:

Pulse offers a lot to any web developer, whether they are building a game or an application. With this just being the developer preview, who knows what may be in store for the future. I know we will be keeping a close eye out here at Switch On The Code.

For more information on Pulse, visit the website and sign up for updates.

Disclaimer
We try to be impartial when reviewing or evaluating products like this. That being said, Pulse is being developed by the same team that created Switch On The Code, so of course we're only ever going to have good things to say about it.


Author: "The Hairiest" Tags: "Tech News"
Comments Send by mail Print  Save  Delicious 
Next page
» You can also retrieve older items : Read
» © All content and copyrights belong to their respective authors.«
» © FeedShow - Online RSS Feeds Reader