Reuse and Recycle: SVG

SVG has had a long and strange journey to the world of ‘emerging technologies” SVG was actually defined in 1999, so it’s not exactly the new kid on the block. Still, it took a while to catch on, so in some ways it feels like the new kid on the block. Like Canvas, SVG allows developer sot create graphics in the browser using native web technologies. Unlike Canvas SVG is a vector based grammar and, since it’s defined as XML it also allows for access using common DOM manipulation tools. One of the most difficult issues when dealing with Canvas is the need to manually manage the state, properties and events of individual elements. Since SVG elements are simple DOM elements, properties are stored as part of the regular DOM and access to individual elements is available using traditional DOM access methods like document.geElementById and document.getElementsByTagName.

One driver of popularity for SVG has been the emergence the RaphaelJS library. Raphael provides a convenient API on top of the specification and provides some measure of support for legacy IE browsers by rendering the output of Rapehl instructions as Vector Markup Language (VML.)

The following example shows Raphael and SVG in action. Example output can be seen in the following figure.
Created with Raphaël 2.1.0

The following code sample illustrates using Raphael to draw 10 random circles on an SVG element, filling them with a random gradient fill. The code is quite simple, with a new paper variable containing the instance of Raphael in use and then straightforward methods circle() and attr() used to create circles and fill them with the fancy gradient fill.

<!DOCTYPE html>
<html>
<head>
  <meta charset=UTF-8">
  <title>SVG</title>
</head>
 <style type='text/css'>
    #svg {
    width:100%;
    height:600px;
}
  </style>
</head>
<body>
  <div id="svg"></div>
  <script src='https://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js'></script>
  <script src='demo.js'></script>

</body>
</html>
window.onload=function(){
var svg = document.getElementById("svg"),
    paper = Raphael( svg ),
    circle,
    width = svg.offsetWidth,
    height = svg.offsetHeight;

for (var i = 0; i < 10; i++) {
  circle = paper.circle(
    parseInt(Math.random() * width), 
    parseInt(Math.random() * height ), 
    parseInt(Math.random() * 200));
  circle.attr({
    "fill": "r" + hex() + "-" + hex(),
    "fill-opacity": "0.5",
    "stroke": "none"
  });
  circle.click(function() {
    console.log(this);
    this.animate({
      cx: parseInt(Math.random() * width),
      cy: parseInt(Math.random() * height),
      r: parseInt(Math.random() * 200)
    }, 1000, "bounce")
  });
}

function hex() {
  //http://paulirish.com/2009/random-hex-color-code-snippets/
  return '#' + Math.floor(Math.random() * 16777215).toString(16);
  }
}

Inspecting the output the underlying markup isn’t quite so succinct, although it should be readable if you’re familiar with XML syntax and can follow along with the code that generated the example. The following code sample shows a single circle marked up using SVG syntax.
The interesting pieces to note are the definition of the radialGradient in the defs element. defs are used for reusable content. You can see it referred to in the circle element’s fill url.

<svg height="400" version="1.1" width="400" xmlns="http://www.w3.org/2000/svg" style="overflow: hidden; position: absolute; left: 0px; top: 0px;">
  <desc>Created with Raphaël 2.1.0</desc>
  <defs>
    <radialGradient id="0r_7d7f2f-_bbb372" fx="0.5" fy="0.5">
      <stop offset="0%" stop-color="#7d7f2f"/>
      <stop offset="100%" stop-color="#bbb372" stop-opacity="0.5"/>
    </radialGradient>
  </defs>
  <circle cx="170" cy="68" r="61" 
          fill="url(#0r_7d7f2f-_bbb372)" 
          stroke="none" 
          style="opacity: 1; fill-opacity: 1;" 
          opacity="1" fill-opacity="1"/>
</svg>

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>