Reuse and Recycle: The Canvas 2D API

The canvas element and associated API started life as an Apple extension to HTML. From there it blossomed into one of the early stars of the HTML5 era. The canvas element provides a scriptable interface for drawing two-dimensional images in the browser. Even without full browser support on the desktop, developers have embraced canvas fully. It’s been used for everything from high traffic visualizations to game engines, a popular system for delivering custom fonts, and a port of the Processing programming language into JavaScript.

While the true power of the Canvas 2d API is beyond the scope of this higher level introduction, it’s worth looking at the API in brief, if just to get a flavor for what it looks like. The following code sample shows a small canvas element and associated JavaScript that draws out a tic-tac-toe game. The simplest piece is the canvas element itself. A canvas element operates much like any other replaced element like a video tag or an image. The big difference is that it lacks a src attribute. The “src” of the canvas image is provided by JavaScript.

<!doctype html>
<html class="no-js" lang="en">
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="_assets/css/style.css">
</head>
<body>
<header>
  <h1>Mobile Web App Cookbook, Canvas</h1>
</header>
<canvas id="ctx" height="300" width="300"></canvas>
<footer>
  <p>&copy; <a href="https://htmlcssjs.wpengine.com/" rel="me">Rob Larsen</a></p>
</footer>
<script src="_assets/js/libs/jquery-1.7.1.min.js"></script>
<script>
//canvas script follows below
</script>

</body>
</html>

The Canvas API is illustrated the in the following script block. It starts by getting a reference to the context of the canvas element. The context is where information about the current rendering state of the element is stored. It contains both the pixel level state of the image as well as various properties and access to core canvas methods used to further manipulate the image. After that you’ll see a variety of basic drawing commends. A path is created using the ctx.beginPath() method and then several context level styles are set. Following that a simple for loop is used to draw lines at regular intervals on the screen. The combination of moving the insertion x/y point of the drawing using ctx.moveTo and drawing the actual line using ctx.lineTo is enough to illustrate the familiar tic-tac-toe board. Following that the “game” is played using a series of text insertions, alternating different fillStyle colors between “turns.”

$( document ).ready(function(){
  var ctx = document.getElementById( "ctx" ).getContext( "2d" ),
  width =  document.getElementById( "ctx" ).width;
  //draw the board
  ctx.beginPath();
  ctx.strokeStyle = '#000';
  ctx.lineWidth = 4;
  for ( var i=1; i < 3; i++ ){   
    ctx.moveTo( ( width / 3 ) * i, 0 );
    ctx.lineTo( ( width / 3 ) * i , width );
    ctx.moveTo( 0, ( width / 3 ) * i );
    ctx.lineTo( width, ( width / 3 ) * i );
  }
  ctx.stroke();
  ctx.closePath(); 
  //"play" the game in order
  ctx.font="80px Arial, Helvetica, sans-serif";
  ctx.fillStyle="#c00";
  ctx.fillText( "x", 130, 170 );
  ctx.fillStyle="#000";
  ctx.fillText( "0", 30, 70 );
  ctx.fillStyle="#c00";
  ctx.fillText( "x", 30, 170 );
  ctx.fillStyle="#000";  
  ctx.fillText( "0", 230, 170 )
  ctx.fillStyle="#c00";;
  ctx.fillText( "x", 130, 70 );
  ctx.fillStyle="#000";  
  ctx.fillText( "0", 130, 270 );
  ctx.fillStyle="#c00";
  ctx.fillText("x", 230, 70 );
  ctx.fillStyle="#000";  
  ctx.fillText( "0", 30, 270 )
  ctx.fillStyle="#c00";;
  ctx.fillText( "x", 230, 270 );
});

This is a simplistic example but it should illustrate the flavor of the API and, hopefully, will get you excited to use some more advanced features.

#$#@ It, We’ll Do It Live.

First off, Happy New Year!

Second off, I finished my second book.

Third off, I’m starting a new job on Monday. More on that later. Teaser? I’ll no longer have to worry about looking too nice at work.

Fourth off, I’m going to try to rework all of my sites this year. Oh snap. I’m starting with this site since it should be a manageable task. I’m working with Skeleton to create a fancy, modern, responsive web site.

Just like the big kids.

As you can see, I’ve already flipped the switch. Release early and often? Something like that. I’m going to customize it over the next few weeks, but after a few hours of tinkering it’s fine for human consumption (that means you, human.)

And, there you have it.

And… the source for the title of this post (NSFW)

Goodbye Sapient, Hello… Free Agency?

It’s true. I’m not sure what the next thing is going to be yet, but I’ve given my notice at Sapient. My last day will be the 30th of November.

Why?

Sapient is an incredible company and the people there are great, but the role wasn’t a great fit with my current interests and long-term goals. It’s been a great experience, but, after taking some time to think about it in between spoonfuls of Roman gelato, I decided that it was time to move on to something new. It’s been a hard decision since the team we’ve built here is so great, but I’m confident this is the best direction for me right now.

Free Agency?

So, why not wait it out until I have that something new in place before giving notice? Why not? I’ve got some money saved up, I haven’t had any break in between jobs since 2006 and I’d like to focus completely on finding the right opportunity without having to fit it in in the middle of a high intensity full-time job.

What’s next?

While my intent is to find another full-time job, I’m also completely open to freelance opportunities, so if you’ve got either a full-time role for a senior front end engineer or a really cool freelance project coming up, I’d love to hear about it.

Can we talk?

I’d also like to get out and do some presentations. I’ve had just a handful of opportunities over the past year, so if you’re running a conference, user group or are an organization looking to bring someone in to talk about emerging web technologies, I’d love to hook you up with the good stuff.

Reuse and Recycle: A Quick Intro to Microdata

Microdata

HTML5 defines a standardized scheme for marking up and retrieving metadata in the body of an HTML document. If you’ve worked with microformats like hCard and hCalendar then microdata will be relatively familiar. The biggest change is the move from the class name hijacking central to microformats to a new itemprop attribute. In addition to this designed solution Microdata adss two new attributes and one dom method that provides standard access to microdata. itemscope sets the scope of a microdata segment, itemtype defines a URL for the microdata format in use and document.getItems() provides access to microdata. The method returns a NodeList containing the items corresponding to an optional itemType argument or all types, if no argument is provided. the following code listing shows a sample document that features a simple bio of your humble author marked up with microdata. It leverages microdata formats from schema.org and mixes and matches three separate microdata formats, Person, Postal Address and Organization.

<!doctype html>
<html class="no-js" lang="en">
<head>
  <meta charset="utf-8">
  <title>Microdata  Example</title>
  <link rel="stylesheet"  href="_assets/css/style.css">
  <script src="_assets/js/libs/modernizr-2.0.6.min.js"></script>
</head>
<body id="microdata">
  <div  id="main">
    <div itemscope  itemtype="http://schema.org/Person">
      <h1  itemprop="name">Rob Larsen</h1>
      <img  src="http://gravatar.com/avatar/88218052898935c38927c1a5e607c794?size=420"  itemprop="image" />
      <h2  itemprop="jobTitle">Senior Specialist, 
        <span  itemprop="worksFor"><span itemprop="name" itsemscope  itemtype="http://schema.org/Organization">
        Sapient Global  Markets</span></span></h2>
      <ul itemprop="address" itemscope  itemtype="http://schema.org/PostalAddress">
        <li  itemprop="streetAddress"> 131 Dartmouth St. </li>
        <li><span  itemprop="addressLocality">Boston</span> <span  itemprop="addressRegion">MA</span></li>
        <li>Rob's email: <a  href="mailto:jane-doe@xyz.edu" itemprop="email">  rob@htmlcssjavascript.com</a> </li>
        <li>Rob's  Blog: <a href="https://htmlcssjs.wpengine.com/"  itemprop="url">htmlcssjavascript.com</a> </li>
        <li><a  href="http://twitter.com/robreact/"  itemprop="url">@robreact on Twitter </a> </li>
        <li><a  href="https://github.com/roblarsen"  itemprop="url">roblarsen on github</a> </li>
      </ul>
    </div>
  </div>
  <script src="code.jquery.com/jquery-1.7.1.min.js"></script>
</body>
</html>

Reuse and Recycle: The History API

The new history API helps to solve one of the most troubling usability issues with Ajax application development (and Flash before it.) By default, if you use the back button on a single page app, you navigate away from the page in question. The expected behavior is to travel back to the previous state of the application.

This can mean potentially losing dozens or even hundreds of historical interactions.

While it’s true that there are script-based solutions available now to handle dynamic state in an Ajax application, the new HTML5 history API provides a single, standard solution. There’s no more choosing between schemes.

It’s not magical. In fact it leaves quite a bit of work to do. You still have to manage and reacreate application state, storing application data in a series of JavaScript objects that populate the history stack.

The following code sample illustrates a basic example. In this simple page a button click changes the color of the page background. Every time this button is pressed the history.pushState method is called. It accepts three arguments, an object representing the history state, a title for the state and a new URL to display in the browser.  The state is the most important argument. In this case it’s simply an object with one property color whose value is the new hex value of the page background. It should represent whatever info you need to recreate that state in the history stack.

To do that, you need to bind a function to the popostate event. This function process the same state passed into history.pushState. In this simple example it just reads the color property but it could do anything needed to rebuild application state. In this example we’re accessing the data in e.originalEvent because of the way that jQuery handles events. The abstraction/compatibility layer on top of the standard event handling buries the original event data one layer down. If you were binding events with window.addEventListener you could skip e = e.originalEvent.

<!doctype html>
<html>
<head>
  <meta  charset="utf-8">
  <title>History Example</title>
</head>
<body>
  <div id="main">
    <button  id="historymaker">click to add to the history stack</button>
    <p  id="reporter">The Background color is #ffffff</p> 
  </div>
  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
  <script>
    $( document  ).ready(function(){
      $(  "#historymaker" ).on( "click" , function(){
        //http://paulirish.com/2009/random-hex-color-code-snippets
        var color  = '#'+Math.floor( Math.random()*16777215  ).toString( 16 ) ;
        $( "body"  ).css( { "background-color" : color } );
        $(  "#reporter" ).text( "The background color is " + color );
        history.pushState(  { "color" : color }, color, color.slice( 1 , color.length  )+".html" ); 
      })

      $( window ).on(  "popstate" , function( e ){
        e = e.originalEvent;
        if ( e.state !== null  ){
          $( "body"  ).css( { "background-color" : e.state.color } ); 
          $(  "#reporter" ).text( "The background color is " +  e.state.color);
        } else {
          $( "body"  ).css( { "background-color" : "#fff" } );
          $(  "#reporter" ).text( "The background color is #ffffff" );
        }
      });

   });
</script>
</body>
</html>