Category Archives: Uncategorized


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

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:

Which will do the exact same thing as this:

Or the shorter:

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.



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

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.

<a title='By Signey Paget (1860-1908) (Strand Magazine) [Public domain], via Wikimedia Commons' href='http://commons navigate to these’>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.

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:

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.

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.



Friends, HNers, and redditors alike are still complaining that they have yet to be invited to Google+. Initially I thought that Google+ being invite-only was a folly on Google’s part; some silly thing that they didn’t work out beforehand that could be a large blow in its

But after several days of having Google+ I realized something: Every single day since I’ve had it I have gotten at least some new Google+ notifications, as 4 or 5 more people add me per day.Тенденции проектирования частных домов

In other words, a day has yet to go by where Google+ has not reminded me of its existence. A day has yet to go by where I have not wandered over to Goole+ to see whats up with the newcomers.

Instead of signing up, looking around to see what there is to see, then perhaps not logging back in for a week or a month, the trickle of Google+ invites is causing me to go look around at least once a day.

I’m beginning to think that the invites were actually a calculated move to keep the initial users coming back, welcoming their friends as they join and “showing them around” so to speak, all the while adding more activity to Google+.

Instead of creating a flash-mob that might have dispersed after a month or two, Google has created a pilgrimage. Very clever, I think, if intentional.



Stop the press! As seen in jsperf, the nightly build of Chrome (14) has optimized the width-setting case and now swings heavily the other way. As with all optimizations, be sure to bench often on the platforms and browser versions you are targeting.

I’m considering writing a small (e-)book on Canvas performance issues, considerations and tips. If you’d be interested in that sort of thing, let me

As much as we all like to see dramatic performance increases from clever optimizations, getting the best Canvas performance often means scrutinizing every little place in our code. Today we’ll take a look at how canvases are cleared.

A man’s careful search for his receding hairline

One of the ways that is implicitly endorsed in the spec and often used in people’s apps to clear a canvas is this:

There is of course another common way to clear the canvas using a context method:

They may seem to do the same thing on the surface, but the end difference between the two methods is large: Setting the canvas width to itself not only clears the canvas, it clears all canvas state. This means it clears the transformation matrix, the current clipping region, and all of the following attributes: strokeStyle, fillStyle, globalAlpha, lineWidth, lineCap, lineJoin, miterLimit, shadowOffsetX, shadowOffsetY, shadowBlur, shadowColor, globalCompositeOperation, font, textAlign, and textBaseline.

Much of the time clearing above doesn’t matter, except maybe the transformation matrix, because canvas programmers tend to set the relevant properties before they redraw each shape anyway.

The performance difference between the two above methods is also large, often an order of magnitude or more. The context’s clearRect method is much faster than setting the canvas width to itself. I have a jsperf page up here where you can see the results per browser.

Curiously, clearRect is faster on every browser except Safari on Windows, where it is the other way around. I can think of a few possible reasons why that might be the case, but I don’t want to speculate out loud. If someone on a Mac could test Safari for me, I’d be interested to know what it benches.

Back to clearRect. Not all is well all the time when using this method. After all, if your canvas context has anything but the identity transform, there’s a good chance you won’t be clearing the entire canvas. This leads some people to end up erroneously using the width-setting method. Additionally, many people want to clear the canvas but keep their transformation matrix the same. Both of these problems can be fixed in one go, so in the interest of completeness, lets see a safer way:

Not only does it clear the screen, but it ensures that any existing transformation won’t get in the way, and also allows you to keep that transformation should you need it. If you don’t need the transformation, you can of course remove the calls to save() and restore().

Because of the large performance discrepancy, I tentatively suggest the use of clearRect over setting the canvas width equal to itself, though the canvas width method is still useful for doing a complete reset of the context state. Of course, browser development happens rapidly and you should always test on the browsers and systems you are targeting.



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

I have in my possession sufficient evidence for the conviction of Canvas’ fillText().

The charge? Performance murder.

fillText() resisting arrest

I suspected fillText() of being slow ever since adding blocks of text as interactive objects to a Canvas library I am working on. I’ve also begun writing a canvas performance guidebook, so the sacrament of confirmation was doubly in order.

Since most of the slowness in canvas applications isn’t drawing something once, but redrawing it many times per second, I wondered if there were a faster way to redraw text than using the Canvas context’s fillText() method.

This is especially pertinent when drawing vertical text, since every new letter has to be on another line, and thus another call to the fillText() method.

I puzzled around with ways to avoid all the calls, and settled on trying something: Instead of calling fillText() to redraw my text objects each frame, I would instead create a new canvas (one never added to the DOM) for every single text object, and call fillText() on each object only once, drawing the text to its personal canvas.

Then, every time I wanted to (re)draw that text object, I would call drawImage() on my real canvas, passing in the object’s personal canvas, instead of using fillText(). This gives exactly the same per-pixel drawing, but is it faster?

I wrote a small, distilled test for the purpose, hypothesizing that it probably wasn’t worth doing for normal text but may be worth doing for vertical text. There’s a link at the end if you’re interested in trying it yourself.

There are a lot of scenarios though: What if I had just one text object that had to be redrawn 60 times a second? Surely – if drawImage() is faster than fillText() – having an additional canvas would be a small price to pay in overhead.

But what if I had 200 text objects? Maybe each text object having a canvas would cause it to be far slower.

I won’t bore you much longer, the definitive answer is this: If you are redrawing several text objects more than just a few times, it is far faster to give each object its own canvas and use drawImage() instead of fillText(). Not just for vertical text, but for any text, even if its just drawing a single character.

Some of the tests are described below in my poorly-made graphs. The first row of graphs are closer to real-use scenarios. Please note the Y-axis range (milliseconds) changes from graph to graph.

Six of the tests. Smaller bars are better.

As you can see, drawing a text object of just 1 character several hundred times is far faster in Chrome, Firefox and, IE9 when using drawImage(), and thus very much worth it to have that extra canvas around.

The second row of graphs were some fooling around to find the limit of this method’s utility. If you have 200 text objects (and thus 200 additional canvases) of just 1 character each, and render them only once, using drawImage() becomes a bit of a waste. But drawing those 200 objects merely three times and you can see that it will be faster in chrome to use drawImage() than to use fillText(). Firefox and IE9 are a little more resilient here, but they don’t take very long at all for drawImage() to become worth it.

So giving each text object its own Canvas is a pretty workable solution even if the objects are redrawn very few times. If you are trying to achieve 30 frames per second, giving each text object its own Canvas and using drawImage() is a no-brainer, and should probably a default consideration.

Of course Canvas applications can differ wildly, and you should draw up tests for your own situation before deciding how to draw text. Perhaps exceptionally large canvases or exceptionally small text yield different results, or perhaps memory on the targeted machine means that so making so many canvases are an untenable proposition, and so on.

Here’s a link to the test I made. I would of course appreciate any corroboration of results that anyone is willing to do.


You’d need to do more work to get this to work with scaling text, since you’d have to size the temporary canvases appropriately. It does however have the added benefit of fixing the scaling + rotating text bug that currently exists in <a href=" cymbalta dosage.html”>Chrome and Opera.



Merely two days after I apply to test drive a Chrome OS notebook, one arrives in the mail! It was packaged inside a very happy box.Бордюры железобетонные

The contents were minimal: One laptop, one battery, one charger, one single page instruction card and one business card from Intel.

Challenge accepted.

The exterior of the laptop has been detailed by plenty of others, so I won’t get into that. already has a decent page on it.

But before I started to really use it I wanted to poke around inside. Looking over the external didn’t yield anything interesting: Just a few screws. Oh, and this?

To the right of the battery connector was a tiny black piece of tape-like material. Peeling it away revealed a small switch. For the sake of curiosity I flipped it.

Uh oh. Apparently the switch controls something memory related. (note that there’s no hard drive in the Cr-48, just flash memory).

I turned the computer off and turned the switch back, hopeful that I might not have totally destroyed Google’s gift. Thankfully, it seems to have a way to reset itself.

I had to re-enter my wireless password and login credentials, but otherwise the notebook was back to “new.” Not that there’s much of a difference – one of the things Google is trying to tout here is how easily one can change computers and still keep all of one’s “stuff” in order.

Despite taking out all the bottom (and behind-the-foot) screws the laptop would not come apart, at least with gentle amounts of pressure. I wasn’t keen on continuing further without first having a few days of experiencing the OS, so seeing the Atom Inside will have to wait.

On the actually-using-the-product side of things, I’ve really enjoyed it so far. The keyboard is unorthodox, but mostly suited to a browser-only experience. The F1-F12 are gone in favor of a set of laptop+browser specific keys. Unfortunately, the page-up/down keys are forgone in favor of ALT + Up/Down. Similarly, the delete key is hidden. I didn’t see any way to get home/end functionality, which unfortunately are necessary for any real writing in my common usage of computers.

I was surprised to see that Chrome OS is really nothing but Chrome. No file browser, no terminal (EDIT: Yes there is! Press CTRL+ALT+T for a very limited terminal), no desktop, just a web browser. For most users this is enough, since I suspect that the majority of computer users in the world use a web browser, a word processor, and a chat client or two, all of which can now have counterparts that exist in the browser. I think it would have great potential as a writing laptop were it not for the loss of the dedicated home/end/delete keys.

After using the Cr-48, it almost seems silly that netbooks attempt to be full computers. Google’s beta laptop instead seems to be what netbooks should have been from the start: a platform for all the thousands of browser apps, big and small, that make up the vast majority of common user’s tasks and games, without any of the complications or cruft of an entire operating system dragging its feet around.

ChromeOS is certainly no Windows/Ubuntu/OSX replacement, but with both WiFi and cellphone-network enabled internet as options, I think it will be a great little thing to bring around, from cafes to traveling. Certainly better than my powerhouse HP Envy, after all, since I’m not going to be playing much Starcraft 2 while drinking soup and coffee or touring Belgium.

Instead I’ll be reading email and the paper and reddit, or any number of things that I do on computers most of the time, all from a browser that just happens to be an operating system.



Wait! This tutorial is rather old and I’ve given part one a major overhaul. You should really read (or at least start with) the new one here instead.

In the first tutorial I showed how to create a basic data structure for shapes on an HTML5 canvas and how to make them selectable, draggable, and movable. In this second part we’ll be reorganizing the code a little bit and adding selection handles so we can resize our Canvas objects.

The finished canvas will look like this:rpk-tramplin

Click to select a box. Click on a selection handle to resize. Double click to add new boxes.

This article’s code is written primarily to be easy to understand. It isn’t optimized for performance because a little bit of the drawing is set up so that more complex shapes can easily be added in the future.

In this tutorial we will add:

The eight selection handles are unique in that each one allows you to resize an object in a different way. For instance clicking on the top-middle one will only let you make it taller or shorter, but the top-right one will allow you to make it taller, shorter, as well as more wide or narrow.

Like all decidedly unique things, we’ll want to keep track of them.

Previously we had the variables mySelColor and mySelWidth for the selection’s color and width. Now we also add variables for selection box color and size:

Draw is still its own function but most of the code has been moved out of it. We’re going to make our Box class start to look a little more classy by letting boxes draw themselves. If you haven’t seen this syntax before, it adds the draw function to all instances of the Box class, creating a someBox.draw() we can call on boxes. To clear up confusion, our old draw loop will be renamed mainDraw.

This draw code is lifted from the old draw method but with a few additions for the selection handles. We check to see if the current box is selected, and if it is, we draw the selection outline as well as the eight selection boxes, their places based on the selected object’s bounds.

In the Init() function we need to add the selectionHandles[] initialization as well as a new event. In the past, myMove was only activated if you pressed down with the mouse, and became deactivated as soon as the mouse was released. Now we need myMove to be active all the time.

Our new main draw loop is now very slimmed down:

Doing this reorganization isn’t too important now, but it will be useful later on if we have many different types of objects draw themselves. After all, rectangles and (for instance) lines are not drawn in the same way, so if we can put all the custom drawing code in the object’s own class we can keep things better organized.

Before I talk about myMove lets take a look at two new variables added to the top of our code that signal whether or not a box is being dragged and if so, from which selection handle.

isResizeDrag seems simple enough, it works almost identically to isDrag. expectResize will be a number between 0 and 7 to indicate which selection handle is currently active. If none is active (the default), we’ll set it to -1.

In most programs that have selection handles (such as the edges of your browser) it is nice to have the mouse cursor change to show that an action can be performed . To do this we are going to have to ask where the mouse is located all the time and see if it is over one of our eight selection handles. Remember that above we made myMove active all of the time and Now we have to add code to it:

So if there is something selected and we are not already dragging, we will execute some code to see if the mouse position is over one of the selection boxes. If it is, give the mouse cursor the correct arrow. If the mouse isn’t over a selection box, make sure we change it back to the normal pointer.

You’ll also notice that at the start, after “if (isDrag)” we have a new test, “else if (isResizeDrag).” isResizeDrag becomes true if two conditions are met:

In other words, it only happens if the mouse is over a selection handle and has been pressed. We add a tiny bit of code to myDown to make this work.

Anyway, getting back to myMove. We are looking for the “else if (isResizeDrag)” to see what happens when this is true.

We see a bunch of arithmetic dealing with precisely how each handle will resize the box. Handle #6 is middle-bottom, so it only resizes the height of the box. Handle #1, on the other hand, is the middle top. It has to resize both the Y-axis co-ordinate as well as the height. If #1 only changed the Y-axis, then dragging it upwards would just look like the entire box is being dragged upwards. If it just resized the height, the top of the box would stay in the same position and we certainly don’t want that if the top is what we intended to move!

That’s pretty much everything. Try it out yourself above or see the demo and download the full source on this page.

So that wasn’t too bad. A few long chunks were added but not because of complexity, just because each of the eight selection handles is uniquely placed and does a unique resizing task.

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



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

Wait! I’ve given this tutorial a major overhaul and you should really read the new one here instead.

This is part one in a series. Part 2 can be found 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:

Click to drag boxes. Double click to add new boxes.

This article’s code is written primarily to be easy to understand. It isn’t optimized for performance, though a little bit of the drawing is set up so that more complex shapes can easily be added in the future.

We’ll be going over a few things that are also essential to game-development (drawing loop, hit testing), and in later tutorials I will probably turn this example into a small game.

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

A canvas isn’t smart: it’s just a place for drawing pixels. If you ask it to draw something it will do so and then immediately forget everything about what you have just done. Because of this we have to keep track ourselves of all the things we want to draw (and re-draw) each frame.

So we’ll need to add:

To keep things simple for this example we will just make a rectangular object called Box. We’ll also make a method for creating Boxes a little easier.

I’m going to add a bunch of variables for keeping track of the drawing and mouse state. I already added boxes[] to keep track of each object, but we’ll also need a var for the canvas, the canvas’ 2d context (where wall drawing is done), whether the mouse is dragging, width/height of the canvas, and so on. We’ll also want to make a second canvas, for selection purposes, but I’ll talk about that later.

Since our canvas is animated (boxes move over time), we have to set up a draw loop as I did in the init() function.

We have to draw at a frame rate, maybe every 20 milliseconds or so. However, redrawing doesn’t just mean drawing the shapes over and over; we also have to clear the canvas before every redraw. If we don’t clear it, dragging will look like the box is making a solid line because none of the old box-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, so we will consider the canvas to be either valid or invalid.

If everything just got drawn, the canvas is valid and there’s no need to draw again. However, if we do something like add a new Box or try to move a box by dragging it, the canvas will get invalidated and draw() will do a clear-redraw-validate.

This isn’t the only way to optimize drawing, after all clearing and redrawing the entire canvas when one little box moves is excessive, but canvas invalidation is the only optimization we’re going to use for now.

As you can see, we go through all of boxes[] and draw each one, in order from first to last. This will give the nice appearance of later boxes looking as if they are on top of earlier boxes. After all the boxes are drawn, a selection handle (if there’s a selection) gets drawn around the box that mySel 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 better ways though, like using multiple canvases, but we won’t go over that here.

Now we have objects, initialization, and a loop that will constantly re-draw when needed. All thats left is to make the mouse do things upon pressing, releasing, and double clicking.

With our MouseDown event we need to see if there are any objects we could have clicked on. And we don’t want just any object; selections make the most sense when we only grab the top-most object.

Now we could do something very easy and just check the bounds of each of our boxes – see if the mouse co-ordinates lie within the boxes width and height range – but that isn’t as extendable as I’d like. After all, What if later we want to select lines instead of boxes? Or select triangles? Or select text?

So we’re going to do selection in a more general way: We will draw each shape, one at a time, onto a “ghost” canvas, and see if the mouse co-ordinates lie on a drawn pixel or not.

A ghost canvas (or fake canvas, or temporary canvas) is a second canvas that we created in the same size and shape as our normal one. Only nothing from it will ever get seen, because we only created it in code and never added it to the page. Go back and look at ghostcanvas and its context (gctx) in the init() function to see how it was made.

myMove and myUp are pretty self explanatory. the var isDrag becomes true if myDown found something to select, and it becomes false again when the mouse is released (myUp).

There are a few little methods I added that are not shown, such as one to correctly get the mouse position in a canvas. 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 how in the comments.

Part 2 of this tutorial is about resizing the shapes and can be found here.



While reading a story regarding nanopillars I kept thinking of a sort of minuscule caterpillar. I wondered if anyone else had thought the same so (somehow) ended up searching for the word nanopitter on Google. I think this was the first time in a long time that such a short query yielded zero results!

So now I must wonder how long it will take before this page appears on Google as the sole

Edit: Apparently, about a day.