Standard advice

Be positive.

Listen for 90% of a conversation and people will find you interesting.

Learn to ask engaging questions and let others do the answering. Don’t just ask people about facts, ask for their opinions too. Don’t be an interrogator. Be curious. Where were you before you were here?

Never criticize, condemn, or complain. Praise people a lot. Learn to spot good looks and compliment them.

Clean yourself up. Don’t skip showers. Care about how your hands and your hair look. Care about clothes. Care about as much as possible. Care about sports, care about elections, care about cars, care about how the sidewalk looks. Care about Rwanda and the Greek debt crisis. Care about backgammon and the nature of games. Never, ever expect anyone else to care.

Find out what they do care about and ask them about it. Try to care about that.

Don’t make every joke you could possibly make. A careful or clever observation will always be a better utterance than “that’s what she said.” Don’t use sarcasm. Strive for sincerity.

Don’t say every sentence that comes to your mind. Think signal to noise ratio. Say just enough to be interesting.

Don’t tell stories that aggrandize yourself. Never tell anyone how good you are at anything. I don’t care if you’re the best billiards player in the world. You can say “I like billiards” and that’s it. I’m serious. Never tell anyone how good you are. If you’re good, they’ll tell you. You can always let them see you in action, but never show off. Never expect a crowd. Be modest.

The person who says they like bowling and then bowls six strikes is more impressive than a person who claims to be amazing at bowling and then bowls ten strikes. Expectations mean a lot.

Understand more about where you live. Take your bike all over town. Ride to the end of the line. Walk around on foot. Look up reviews on every single restaurant even if you never go to them. Read the menus. Dine alone. Offer to go to breakfast together. Visit the city. Visit the country. Visit the mountains.

Spend a lot of time at the ocean-side. Run around on the beach like an idiot. Run around in the waves. Swim until you’ve dreamed too much about what’s below the ocean. Build a trench, be a soldier. Build castles, be a king. Watch how easily the castle fades away if you don’t protect it. Think of your investments, metaphorical or not. Remember Borges:

“Nothing is built on stone; all is built on sand, but we must build as if the sand were stone.”

Many things wash away naturally, you should allow the same. Forgive often.

Realize that you gain nothing from being shy. That doesn’t mean you have to start making speeches in front of crowds. It means you have to be as open and honest as you plainly can be. There’s nothing wrong with emotions and there’s nothing wrong with telling people how you feel about something. No one can ever contest how you feel. Being an open book may sound like a vulnerable position to be in, but it is the exact opposite.

Spend money on experiences and not things. Read more books. Have what she’s having. Make things, always make things, physical things, even if its just paper cranes and home-cooked meals. Create and share. Understand that most people won’t give a damn. That’s okay. Always create. Enjoy the beauty of it.

Move to a not-suburb. Join meetup.com or grubwithus.com or whatever is in the paper. Knitting clubs aren’t about knitting, they are about socializing. Take pottery/archery/tennis/anything classes. Join a club soccer team. Visit the same cafe at least once a week. Jog through the park. Smile at everyone. Literally put yourself out there. Be discover-able. Be friendly.

Be positive.

In short, remember: Smile, eyes, build, butt. Be happy. Be sincere. Take care of yourself. Dress well.

Why I Love Recruiters

Right now there’s a front-page article on HN titled “Why I Hate Tech Recruiters” relating one person’s disdain of an offhanded recruiter email. The comments replied with their own horror stories and distaste for the profession.

While offhanded emails are among the worst of all mail I don’t think it is reason alone to condemn all recruiters to being a scorned class. I love recruiters. Really. Any sincere effort from one I take as a kind of compliment. A compliment, no less, from a field that takes a serving of hostility and non-replies as their mid-day meal. The best recruiters brighten my day and the least I could do is be pleasant in return.

I get a “real” inquiry maybe about once a week (being from the mere hills of New Hampshire and notable for only one niche I find even this amount surprising) but I try to always take the time and give a reply. If the recruiter hasn’t shown much effort I copy and paste something suggesting that a more sincere letter would yield more sincere replies. If I don’t have the time, I can always delete them. Deleting an errant email is an easy thing.

Being a good recruiter is probably less-easy and I imagine that when we come across them we should do our part to reward them somehow, even if we aren’t interested in the position. If the recruiter has shown some effort then I feel obliged, time permitting, to give them something in return.

The replies I give are always a very roundabout way of declining but it gives me an opportunity to (hopefully) brighten the day of what I imagine is a difficult job that often involves so much hostility or lack of reply from the people they contact. I’d like to think recruiters have feelings, and if they spend the time to craft a sincere request then I will delightedly spend the time to craft at least a partially amusing reply.

How would you like it, after all, if you spend a day crafting thirty good recruiting emails only to be met with an empty (or hostile!) inbox the next morning?

Below are a couple of examples of the sort of things I say in return. Names have been removed for the sake of privacy.


Dearest G-,

I apologize for the late reply. I have been working day and night (and dawn and dusk) as uncountable tasks approach my inbox (and life) in recent times.

While Microsoft is a fine company and I do enjoy my use of the Windows 8 release preview, I cannot accept any offers to apply because Redmond, Washington is very far from New Hampshire and I am the sort to walk to work.

I would perhaps urge you to suggest to the good Microsofters of Redmond to get out of their buildings and attempt to push them closer to New Hampshire but I do not think it is technically feasible, and besides they probably would not agree to do it, as backs would ache in even the best conditions, and New Hampshire is very far.

Perhaps someday I will choose to leave this small town but this year is not the year and so I must decline any offers for the time being.

Please take my kind regards, and the hope that the weather turns to more reasonable temperatures for the both of us,

Simon Sarris


Dearest K-,

Thank you for extending to me this invitation.

Unfortunately for perhaps both of us I live in New Hampshire and intend to remain in New Hampshire for the (metaphorically) foreseeable future. That is not a derision of Wisconsin, which I am sure is wonderful and produces many grand (or Epic) things and people. But while Wisconsin makes many fine and attractive things such as (say) cheeses (Sartori Bellavitano anyone?), trucks are always willing to relocate said cheeses to New Hampshire.

Trucks are less willing or able to move my house to Wisconsin, and even if they were, the Historical Society might raise an objection or two. Moving my friends would be even more difficult, as several of them object to being carried around and placed in other states.

Alas while there may come a time to lead myself from this Maple-syrup laden location, as Syrio says, “Not today.”

I hope your candidate search goes well,

Simon Sarris


S-,

Thank you for your invitation.

However I am comfortably employed (and living) in New Hampshire and do not intend to consider moving in the near future, regardless of that fact that your company and potential jobs may well be very interesting.

Or as our girlfriends of yore might have said, “It’s not you, it’s me.”

Your site is beautiful, by the way.

Hope for the best,

Simon Sarris


Anyway I’m sure not everyone is as easily flattered as I am by a simple piece of mail. But if we have a problem with the recruiting profession then we should do our part to reward the good ones, shouldn’t we?

I’m writing a book!

I’m writing a book!

On HTML5!

You can preorder it on Amazon here.

It will be in full color with plenty of examples and syntax highlighting and in real live bookstores. A large part of the book will be canvas, of course, and I plan for all chapters and subjects to be independent of each-other in case you wish to pick and choose the parts of HTML5 you read about.

Signing the contract means signing away a good chunk of my free time, though, so there may not be any new posts for a while. I’ll still try to squeeze in a blog post here and there, as there have been a lot of very interesting cases I’ve come across helping people with canvas lately.

It’s been a very interesting past two years. I’m now the top answerer for both Canvas and HTML5 on Stack Overflow. I hope I can find the time to continue helping people while I write. And I do try give a thoughtful reply to every question emailed to me, even if it takes some time to respond!


If you want to read my minor thoughts and updates and programming humor in the meantime there is always my Twitter.

That’s all for now!

A Gentle Introduction to Making HTML5 Canvas Interactive

I’m writing a book on HTML5, including Canvas! Click here for more information.

This is a big overhaul of one of my tutorials on making and moving shapes on an HTML5 Canvas. This new tutorial is vastly cleaner than my old one, but if you still want to see that one or are looking for the concept of a “ghost context” you can find that one here.

This tutorial will show you how to create a simple data structure for shapes on an HTML5 canvas and how to have them be selectable. The finished canvas will look like this:


This text is displayed if your browser does not support HTML5 Canvas.

Click to drag the shapes. Double click to add a new shape.


We’ll be going over a few things that are essential to interactive apps such as games (drawing loop, hit testing), and in later tutorials I will probably turn this example into a small game of some kind. The code also contains simple examples of using JavaScript prototypes and closures. I will try to accommodate JavaScript beginners but this introduction does expect at least a rudimentary understanding of JS. Not every piece of code is explained in the text, but almost every piece of code is thoroughly commented!

The HTML5 Canvas

A Canvas is made by using the <canvas> tag in HTML:

   <canvas id="canvas" width="400" height="300">
    This text is displayed if your browser does not support HTML5 Canvas.
   </canvas>

A canvas isn’t smart: it’s just a place for drawing pixels. If you ask it to draw something it will execute the drawing command and then immediately forget everything about what it has just drawn. This is sometimes referred to as an immediate drawing surface, as contrasted with SVG as a retained drawing surface, since SVG keeps a reference to everything drawn. Because we have no such references, we have to keep track ourselves of all the things we want to draw (and re-draw) each frame.

Canvas also has no built-in way of dealing with animation. If you want to make something that you’ve drawn move, you have to clear the entire canvas and redraw all of the objects with one or more of them in a new location. And you have to do it often, of course, if you want a semblance of animation or motion.

So we’ll need to add:

  1. Code for keeping track of objects
  2. Code for keeping track of canvas state
  3. Code for mouse events
  4. Code for drawing the objects as they are made and move around

The things we draw

To keep things simple for this example we will start with a Shape class to represent rectangular objects.

JavaScript doesn’t technically have classes, but that isn’t a problem because JavaScript programmers are very good at playing pretend. Functionally (well, for our example) we are going to have a Shape class and create Shape instances with it. What we are really doing is defining a function named Shape and adding functions to Shape’s prototype. You can make new instances of the function Shape and all instances will share the functions defined on Shape’s prototype.

If you’ve never encountered prototypes in JavaScript before or if the above sounds confusing to you, I highly recommend reading Crockford’s JavaScript: The Good Parts. The book is an intermediate overview of JavaScript that gives a good understanding of why programmers choose to create objects in different ways, why certain conventions are frowned upon, and just what makes JavaScript so different.

Here’s our Shape constructor and one of the two prototype methods, which are comparable to a class instance methods:

// Constructor for Shape objects to hold data for all drawn objects.
// For now they will just be defined as rectangles.
function Shape(x, y, w, h, fill) {
  // This is a very simple and unsafe constructor. 
  // All we're doing is checking if the values exist.
  // "x || 0" just means "if there is a value for x, use that. Otherwise use 0."
  this.x = x || 0;
  this.y = y || 0;
  this.w = w || 1;
  this.h = h || 1;
  this.fill = fill || '#AAAAAA';
}
 
// Draws this shape to a given context
Shape.prototype.draw = function(ctx) {
  ctx.fillStyle = this.fill;
  ctx.fillRect(this.x, this.y, this.w, this.h);
}

They are pretty self-explanatory. The shape constructor has “defaults” if you give it no arguments, and calling draw on a shape will set the fill and draw a rectangle on the given context corresponding to the measurements of the Shape.

Keeping track of canvas state

We’re going to have a second class (function) called CanvasState. We’re only going to make one instance of this function and it will hold all of the state in this tutorial that is not associated with Shapes themselves.

CanvasState is going to foremost need a reference to the Canvas and a few other field for convenience. We’re also going to compute and save the border and padding (if there is any) so that we can get accurate mouse coordinates.

In the CanvasState constructor we will also have a collection of state relating to the objects on the canvas and the current status of dragging. We’ll make an array of shapes to keep track of whats been drawn so far, a flag “dragging” that will be true while we are dragging, a field to keep track of which object is selected and a “valid” flag that will be set to false will cause the Canvas to clear everything and redraw.

I’m going to add a bunch of variables for keeping track of the drawing and mouse state. I already added shapes[] to keep track of each object, but we’ll also need a var for the canvas, the canvas’ 2d context (where all drawing is done), whether the mouse is dragging, width/height of the canvas, and so on.

function CanvasState(canvas) {
 
  // ...
 
  // I removed some setup code to save space
  // See the full source at the end
 
 
  // **** Keep track of state! ****
 
  this.valid = false; // when set to true, the canvas will redraw everything
  this.shapes = [];  // the collection of things to be drawn
  this.dragging = false; // Keep track of when we are dragging
  // the current selected object.
  // In the future we could turn this into an array for multiple selection
  this.selection = null;
  this.dragoffx = 0; // See mousedown and mousemove events for explanation
  this.dragoffy = 0;

Mouse events

We’ll add events for mousedown, mouseup, and mousemove that will control when an object starts and stops dragging. We’ll also disable the selectstart event, which stops double-clicking on canvas from accidentally selecting text on the page. Finally we’ll add a double-click (dblclick) event that will create a new Shape and add it to the CanvasState’s list of shapes.

The mousedown event begins by calling getMouse on our CanvasState to return the x and y position of the mouse. We then iterate through the list of Shapes to see if any of them contain the mouse position. We go through them backwards because they are drawn forwards, and we want to select the one that appears topmost, so we must find the potential shape that was drawn last.

If we find a shape then we want to select it. We save the offset, save a reference to that shape as the CanvasState’s this.selection, set this.dragging to true and set the this.valid flag to false. Already we’ve used most of our state! Finally if we didn’t find any objects we need to see if there was a selection saved from last time. Since we clicked on nothing, we obviously didn’t click on the already-selected object, so we want to “deselect” and clear the selection reference. Clearing the selection means we will have to clear the canvas and redraw everything without the selection ring, so we set the valid flag to false.

 
  // ...
  // (We are still in the CanvasState constructor)
 
  // This is an example of a closure!
  // Right here "this" means the CanvasState. But we are making events on the Canvas itself,
  // and when the events are fired on the canvas the variable "this" is going to mean the canvas!
  // Since we still want to use this particular CanvasState in the events we have to save a reference to it.
  // This is our reference!
  var myState = this;
 
  //fixes a problem where double clicking causes text to get selected on the canvas
  canvas.addEventListener('selectstart', function(e) { e.preventDefault(); return false; }, false);
  // Up, down, and move are for dragging
  canvas.addEventListener('mousedown', function(e) {
    var mouse = myState.getMouse(e);
    var mx = mouse.x;
    var my = mouse.y;
    var shapes = myState.shapes;
    var l = shapes.length;
    for (var i = l-1; i >= 0; i--) {
      if (shapes[i].contains(mx, my)) {
        var mySel = shapes[i];
        // Keep track of where in the object we clicked
        // so we can move it smoothly (see mousemove)
        myState.dragoffx = mx - mySel.x;
        myState.dragoffy = my - mySel.y;
        myState.dragging = true;
        myState.selection = mySel;
        myState.valid = false;
        return;
      }
    }
    // havent returned means we have failed to select anything.
    // If there was an object selected, we deselect it
    if (myState.selection) {
      myState.selection = null;
      myState.valid = false; // Need to clear the old selection border
    }
  }, true);

The mousemove event checks to see if we have set the dragging flag to true. If we have it gets the current mouse positon and moves the selected object to that position, remembering the offset of where we were grabbing it. If the dragging flag is false the mousemove event does nothing.

  canvas.addEventListener('mousemove', function(e) {
    if (myState.dragging){
      var mouse = myState.getMouse(e);
      // We don't want to drag the object by its top-left corner,
      // we want to drag from where we clicked.
      // Thats why we saved the offset and use it here
      myState.selection.x = mouse.x - myState.dragoffx;
      myState.selection.y = mouse.y - myState.dragoffy;   
      myState.valid = false; // Something's dragging so we must redraw
    }
  }, true);

The mouseup event is simple, all it has to do is update the CanvasState so that we are no longer dragging! So once you lift the mouse, the mousemove event is back to doing nothing.

  canvas.addEventListener('mouseup', function(e) {
    myState.dragging = false;
  }, true);

The dblclick event we’ll use to add more Shapes to our canvas. It calls addShape on the CanvasState with a new instance of Shape. all addShape does is add the argument to the list of Shapes in the CanvasState.

  // double click for making new Shapes
  canvas.addEventListener('dblclick', function(e) {
    var mouse = myState.getMouse(e);
    myState.addShape(new Shape(mouse.x - 10, mouse.y - 10, 20, 20,
                               'rgba(0,255,0,.6)'));
  }, true);

There are a few options I implemented, what the selection ring looks like and how often we redraw. setInterval simply calls our CanvasState’s draw method. Our interval of 30 means that we call the draw method every 30 milliseconds.

  // **** Options! ****
 
  this.selectionColor = '#CC0000';
  this.selectionWidth = 2;  
  this.interval = 30;
  setInterval(function() { myState.draw(); }, myState.interval);
}

Drawing

Now we’re set up to draw every 30 milliseconds, which will allow us to continuously update the canvas so it appears like the shapes we drag are smoothly moving around. However, drawing doesn’t just mean drawing the shapes over and over; we also have to clear the canvas on every draw. If we don’t clear it, dragging will look like the shape is making a solid line because none of the old shape-positions will go away.

Because of this, we clear the entire canvas before each Draw frame. This can get expensive, and we only want to draw if something has actually changed within our framework, which is why we have the “valid” flag in our CanvasState.

After everything is drawn the draw method will set the valid flag to true. Then, once we do something like adding a new Shape or trying to drag a Shape, the state will get invalidated and draw() will clear, redraw all objects, and set the valid flag again.

// While draw is called as often as the INTERVAL variable demands,
// It only ever does something if the canvas gets invalidated by our code
CanvasState.prototype.draw = function() {
  // if our state is invalid, redraw and validate!
  if (!this.valid) {
    var ctx = this.ctx;
    var shapes = this.shapes;
    this.clear();
 
    // ** Add stuff you want drawn in the background all the time here **
 
    // draw all shapes
    var l = shapes.length;
    for (var i = 0; i < l; i++) {
      var shape = shapes[i];
      // We can skip the drawing of elements that have moved off the screen:
      if (shape.x > this.width || shape.y > this.height ||
          shape.x + shape.w < 0 || shape.y + shape.h < 0) continue;
      shapes[i].draw(ctx);
    }
 
    // draw selection
    // right now this is just a stroke along the edge of the selected Shape
    if (this.selection != null) {
      ctx.strokeStyle = this.selectionColor;
      ctx.lineWidth = this.selectionWidth;
      var mySel = this.selection;
      ctx.strokeRect(mySel.x,mySel.y,mySel.w,mySel.h);
    }
 
    // ** Add stuff you want drawn on top all the time here **
 
    this.valid = true;
  }
}

We go through all of shapes[] and draw each one in order. This will give the nice appearance of later shapes looking as if they are on top of earlier shapes. After all the shapes are drawn, a selection handle (if there is a selection) gets drawn around the shape that this.selection references.

If you wanted a background (like a city) or a foreground (like clouds), one way to add them is to put them before or after the main two drawing bits. There are often better ways though, like using multiple canvases or a CSS background-image, but we won’t go over that here.

Getting mouse coordinates on Canvas

Getting good mouse coordinates is a little tricky on Canvas. You could use offsetX/Y and LayerX/Y, but LayerX/Y is deprecated in webkit (Chrome and Safari) and Firefox does not have offsetX/Y.

The most bulletproof way to get the correct mouse position is shown below. You have to walk up the tree adding the offsets together. Then you must add any padding or border to the offset. Finally, to fix coordinate problems when you have fixed-position elements on the page (like the wordpress admin bar or a stumbleupon bar) you must add the <html>’s offsetTop and offsetLeft.

Then you simply subtract that offset from the e.pageX/Y values and you’ll get perfect coordinates in almost every possible situation.

// Creates an object with x and y defined,
// set to the mouse position relative to the state's canvas
// If you wanna be super-correct this can be tricky,
// we have to worry about padding and borders
CanvasState.prototype.getMouse = function(e) {
  var element = this.canvas, offsetX = 0, offsetY = 0, mx, my;
 
  // Compute the total offset
  if (element.offsetParent !== undefined) {
    do {
      offsetX += element.offsetLeft;
      offsetY += element.offsetTop;
    } while ((element = element.offsetParent));
  }
 
  // Add padding and border style widths to offset
  // Also add the <html> offsets in case there's a position:fixed bar
  offsetX += this.stylePaddingLeft + this.styleBorderLeft + this.htmlLeft;
  offsetY += this.stylePaddingTop + this.styleBorderTop + this.htmlTop;
 
  mx = e.pageX - offsetX;
  my = e.pageY - offsetY;
 
  // We return a simple javascript object (a hash) with x and y defined
  return {x: mx, y: my};
}

At long last

From here its just a few lines to draw some shapes to move around. We make one instance of CanvasState, passing it a reference to the canvas we want to use, then we can add any number of new shapes to it. The code below produces the example at the top of this page:

var s = new CanvasState(document.getElementById('canvas1'));
s.addShape(new Shape(40,40,50,50)); // The default is gray
s.addShape(new Shape(60,140,40,60, 'lightskyblue'));
// Lets make some partially transparent
s.addShape(new Shape(80,150,60,30, 'rgba(127, 255, 212, .5)'));
s.addShape(new Shape(125,80,30,80, 'rgba(245, 222, 179, .7)'));

There are a few little methods I added that are not shown, such as Shape’s method to see if a point is inside its bounds. You can see and download the full demo source here.

Now that we have a basic structure down, it is easy to write code that handles more complex shapes, like paths or images or video. Rotation and scaling these things takes a bit more work, but is quite doable with the Canvas and our selection method is already set up to deal with them.

If you would like to see this code enhanced in future posts (or have any fixes), let me know.

I’m writing a book on HTML5, including Canvas! Click here for more information and sign up to be notified when it comes out!

The most amazing thing

I live my life in a state of constant, quiet amazement. Almost everything is impressive to me, from the last book I read to the last soup I ate. I don’t get bored, and am often happy to just sit and think about things, pretty much any thing.

It’s just reached midnight in New Hampshire, and “yesterday” the Galaxy Nexus was released for Verizon in the United States.

I’m sure to lots of people this is just yet-another-android-phone. Or for many its simply an upgrade from one gadget to the next. People will yawn, or fawn, or get on with their lives with or without it. I myself would probably be pleased as Punch with just about any modern smartphone.

Yesterday I bought a Galaxy Nexus, my first smartphone and second-ever cellphone.

Learning to set my alarm for tomorrow morning, I find myself reflecting. I really am completely in awe. Starstruck. I am a computer person, and here is a thing more powerful than most of the computers I have ever owned.

In New Hampshire 4G was rolled out Wednesday or so my coworkers tell me. The data capabilities of the phone are impressive to me, but then again 56k speeds on the phone would not be any less impressive. How could they be?

Somehow I have made it almost to 2012 without owning a GPS or an MP3 player or a pocket camera. It’s not that I’m against them, I just never found much need. Now I have a device with a scope and power so large I cannot believe it is this small.

The age of “wondering why” is over. This is instant portable access to the largest knowledge and communication infrastructure in the world. A rough approximation of the sum of human knowledge is literally carried along in my pocket. I can express and communicate and learn from anywhere. At my desk, in my bed, on the road, in the woods.

How is this not the most amazing thing?

Understanding the HTML5 Canvas image security rules

I’m writing a book on HTML5, including Canvas! Click here for more information.

There’s a common point of confusion regarding when one can use HTML5 Canvas getImageData() and toDataUrl() methods. Certain operations will cause these methods to throw a security error instead of functioning normally.

The rules for what one can and cannot do are laid out in the spec, though the reasoning behind them isn’t so obvious. The most typical violation is when a programmer uses drawImage() with an image that is from a different domain (than the page that the canvas is on) or an image that is on the local file system. When drawImage() is used in one of these two ways, the canvas internally sets its origin-clean flag to false.

From the moment a canvas has its origin-clean flag set to false one is not allowed to use the getImageData() and toDataUrl() methods of that canvas, instead the security error will be thrown. There are a few more cases where the origin-clean flag will be set to false, you can read about them in the spec here.

The reason for this security is to prevent something called information leakage. To see why this is a security issue, consider the following hypothetical situation:

Say you are on a work network and so you have access to internal, private company sites and your (private!) hard-drive. The private sites might be something like www.internal.myCompany.com and your hard drive would be accessible from urls like file:///C:/SomeOfMyPhotos/.

Now suppose you visited a website with a hidden canvas and while you were browsing the site that canvas was constantly calling drawImage() onto that canvas with urls that it was guessing might exist. These urls would be things like an image on the private subdomain:

www.internal.myCompany.com/secret/secret-plans.jpg

Or an image on your hard drive:

file:///C:/SomeOfMyPhotos/thatEmbarassingPhoto.png

The malicious site could keep trying different combinations of private-to-you urls until it found one that was actually a file. Then it would draw it to the canvas. Then it would get the imageData from the canvas and send it off to the server.

Voila! The malicious site owner now has your secret plans and your embarrassing photos, much without your consent.

Now we know that the above scenario is not very probable: In the real world, secret plans are almost always in PNG format whereas embarassing photos are almost universally in JPG format! But it stands that situations like the above could happen and so the security implications of canvas must take this into account.

A transformation class for Canvas to keep track of the transformation matrix

I’m writing a book on HTML5, including Canvas! Click here for more information.

The HTML5 Canvas does not have a method for getting the current transformation matrix. For some applications, keeping track of the current transformation matrix would be a nice feature to have.

I’ve made this easier by creating a simple Transform class for use with Canvas. You can have a look at it here.

It has all of the Canvas equivalents, and can be used alongside canvas to record the matrix state or can be used instead of and then applied to the canvas.

In other words, a start-to-finish use of the Transform would be like this:

var t = new Transform();
t.rotate(5);
var m = t.m;
ctx.setTransform(m[0], m[1], m[2], m[3], m[4], m[5]);

Which will do the exact same thing as this:

ctx.rotate(5);

Or the shorter:

var t = new Transform();
t.rotate(5);
ctx.rotate(5);

But of course allow you to keep track of it!

If you wanted, you could easily call the class to take a context and always do the operations when it is called.

Increasing Performance by Caching Paths on HTML5 Canvas

I’m writing a book on HTML5, including Canvas! Click here for more information.

Much of the functionality of Canvas comes from its path drawing functions. Unfortunately for game designers and animators, re-drawing paths over and over can amount to a tangible performance hit. To increase performance, let’s take a look at caching paths as images to avoid redrawing them traditionally.


Paget holmes
Gentlemen waiting for a path to finish rendering

First we need to ensure that caching a path will actually lead to a performance increase. We can devise a simple test for this using JSPerf. We need a path to test, so let’s write something fairly simple.

ctx.beginPath();
ctx.strokeStyle = 'red';
ctx.lineWidth = 4;
ctx.moveTo(10,10);
ctx.lineTo(10,30);
ctx.lineTo(30,30);
ctx.lineTo(40,70);
ctx.quadraticCurveTo(72,43,22,12);
ctx.quadraticCurveTo(12,43,12,102);
ctx.stroke();

This does not produce a particularly complex or exciting path:



But it will do.

The thing we want to ponder here is whether redrawing this path, in other words executing every one of the instructions needed to make the path, will be a slower process than if we cached it. We can achieve caching by drawing the path from these instructions only once, to an in-memory canvas, and then using drawImage from our in-memory canvas onto our real canvas to redraw the path.

That isn’t the only way to cache. We could instead draw it to a canvas and then make a PNG out of it, and call drawImage from that PNG instead, but for the sake of making a simpler test we will stick with using an in-memory canvas.

So let us take all of the drawing instructions above and execute them on the in-memory canvas. Then in our draw loop, instead of drawing out the path every time, we simply draw the in-memory canvas to our real canvas:

// can2 is our in-memory canvas
ctx.drawImage(can2, 0, 0);

The test is simple enough. Giving it a go, the results are immediately clear: pre-rendering and using drawImage is more than ten times as fast as drawing the path, even for the relatively simple path used!



The more complex the path, the more time you will save with caching. If you’re using a lot of complex paths to render shapes, such an optimization ought to speed up your draw loop by a great deal. The JSPerf page shows a simple setup if you want to make the test for yourself.

Other considerations

Pre-rendering paths isn’t a magic bullet, there are still a lot of uses for drawing paths constantly in canvas. If you are making a live drawing application, or otherwise constructing dynamic paths and/or moving and animating paths on the fly, then any kind of pre-rendering is going to be nearly pointless or even harmful to performance. After all, what’s the use of drawing something to a separate canvas and drawing that state back to the original canvas if the path changes constantly? You’d need to re-draw the in-memory canvas just as often, so you’d lose all benefit.

It is also worth mentioning that you might want to play around with using PNGs instead of in-memory canvases. Another thing to test is putting multiple paths onto one in-memory canvas versus putting them all in their own separate canvases, effectively making a sprite sheet. From previous tests, it seems that there is a slight advantage to giving each sprite its own png instead of using a single-png (or single in-memory canvas) sprite-sheet, but it wasn’t that big of a difference.

If you do choose to use a sprite sheet, note that there are a lot of decent tools out there for compressing and organizing them, such as Sprite Sheet Packer.