Category: JavaScript
Jan 5, 2017

Normally in web application development, clicks are a matter of listeners. Either a click hit a thing or it didn’t. When using the HTML5 canvas, this isn’t the case. Images and features are rendered onto it, but you can’t attach a listener to them. Instead, you monitor where these elements visually reside versus where clicks land.

If an object is rectangular and will never rotate, the solution is easy. If click X is between object start X and object end X, and click Y likewise, then it hit. If not, it didn’t.

In this post we’ll construct a simple series of functions for determining the same thing if the rectangle has rotated, then look at how the idea can apply to more complex shapes. Nothing new or groundbreaking, and nothing language-specific — consider this a StackOverflow answer.


For a developer who hasn’t mathed in a while, this can seem tricky at first. Once you see a few images it’s perfectly sensible.

We’ll be drawing four triangles. Each one consists of the click point and two vertices of the object. We then compare the area of the object to the combined area of the triangles. If they’re the same, the click had to be in the object. If the triangles are larger, the click couldn’t have been in the object.

Rotated Rectangle - Click hit

If the click was inside, the areas are equal.

Rotated Rectangle - Click miss

If the click was outside, the combined area of the triangles is bigger than the area of the rectangle.

How much it’s rotated doesn’t matter. Where it’s at doesn’t matter. That’s literally all there is to this.

First things first

To figure out if the click hit, we’ll need four pieces of data:

  • The coordinates of the click
  • The position of the rectangle
  • The size of the rectangle
  • The angle of rotation of the rectangle

Those last three pieces we’re just putting together so we can find the vertices. Once we know the click position and the vertex positions, figuring out if the click hit is easy.

Finding the vertices

Since you’re probably not tracking the individual locations of the vertices and are instead tracking the position of the object, you’ll want to start with a function that can find these by the object’s size and position. How this will be done is hugely variable depending on where you’re measuring from (tracking left top? center?) and if/how the object has been scaled.

If we pretend like there’s no scaling or rotation and we’re measuring from left and top, the function may initially look like this:

Since this doesn’t take into account rotation yet, we’ll need a utility function to find a point’s new location after it’s been rotated by X degrees around another point:

Modifying our previous findRectVertices  function to also use rotation may then look like this, assuming we’re rotating objects around their center:

Calculating the areas

Now that we have all the necessary points, all that’s left are three things:

  • Calculate the area of the rectangle
  • Calculate the area of the triangles
  • Compare the two

If you recall high school geometry, point two is the loaded one there. To find the area of an unknown triangle we’d use Heron’s formula, but first the distances of each side will be needed. The two utility functions may look like this:

With those functions ready, we can now write a complete function that performs the three bullet points and returns a simple True or False:

Common issues

By far the most frequent annoyance with this approach when working in the DOM is going to be getting good position numbers. So many variables can throw a wrench in how you’re measuring where the object is. If your reported object position doesn’t match up with the reported mouse or touch position, all of the above is useless.

Look for situations in which clicking near something instead of on it reports a hit, then try to identify elements that match the size of the inaccuracy. Everything from margins on the HTML or body elements, borders on divs, document scroll position, and box-sizing settings can play havoc on your ability to get clean measurements that match up with what’s plainly visible.

Going farther

This method isn’t just good for rectangles. It would be straightforward to apply to triangles, too, or for any other convex polygon. Consider how you might implement the ability to check if a click landed inside a hexagon. As a brain teaser, what would happen on a concave polygon?

Jan 4, 2017

My team does a holiday card promotion each year, which gives us a chance to create something unusual. This year we decided on a “create your own holiday card” image editor idea. We’d specify a couple of backgrounds and design a bunch of “sticker” graphics, then users could arrange these how they liked and print off a foldable card. Give it a try!

For this project, I created stickerbomb, a one-command in-browser basic graphics editor. It allows you to specify backgrounds and load in as many stickers as you’d like, categorized into drawers. Users can then position and manipulate the stickers however they like. When finished, they can either print it, save it, or share a URL that causes stickerbomb to reconstuct their image.


Give it a shot by designing your own smug tech conference laptop:


The show above would be created like this:

Very easy! All other options can be found on the Github page.

How it works

Stickerbomb is an HTML5 canvas library. It’s plain JS that forms a number of DOM elements as controls around a canvas where it’s watching for mouse and touch movements. Whenever an event occurs on the canvas, it checks whether the selected tool should be instantaneous or work with dragging, and then, if dragging, records the position (relative to the canvas) and angle (relative to the sticker) of the start point and current point. The position information is gathered by the tool, which then uses whatever is applicable to manipulate the layers.

image sharing dialog

Rather than grant full control over positioning, it works on whole percentages. A sticker can be 15% wide, 28% from the left, and 50% from the top, for example. Movement and changes only happen on the whole numbers. This has the twofold benefit of significantly reducing the cost of the rendering loop (as each layer from the background up must be recalculated and redrawn in order on any change to the image) and allowing for very easy reconstruction of any created image. A basic notation of the information above would be w15l28t50, for example. That makes share URLs quite simple, fully client side, and small enough to pack more stickers than you’ll ever need into a URL before length limits become an issue (something like 800).

Printing and the future

One bit of weirdness in the library is its print function. For that it does a hidden, reconstructed rendering of your image in higher resolution, opens a new window with just that image at 100% width and flipped upside down, and then opens a print dialog–which was a proper pain to get working cross-browser. Assuming the aspect ratio is 1.55 this makes for a ready-to-fold card, which was the original goal. It’s not exactly what you’d expect to happen, though, so that may be branched out as its own tool separate from “print” if any future development is done on this.

The likely outcome is that this won’t be significantly developed further, but will result in a few good basic tutorial posts. How to tell if a click landed inside the boundaries of a rotated object, maybe.

Sep 15, 2016

Update:  Now with more style. The most important thing in life is to have your pokémon arranged neatly. That’s a fact. While I understand you can just rename boxes with numbers so that Box 1 is 1-30 and Box 2 is 31-60, etc., there’s still a tiny bit of basic arithmetic slowing down your sorting […]

Continue reading...
Jul 24, 2015

Where I work, we use TERMINALFOUR as our main content management system. It’s a real beast of a CMS targeted at higher education, written in Java, and capable of handling very large, high-traffic sites straight out of the box. The only major hangup is that its normal publish processor for outputting HTML from user content […]

Continue reading...
Fork me on GitHub