ericdrowell/KineticJS — pull request #514 by rradonic (2013-06-28 11:16:10+00:00)
Title: Image distortion implementation

I've added a new option to the Kinetic.Image constructor, called 'distortion'.

You pass in a function that returns four points. It's a function so that the points can potentially change each time the image is rendered. If you think it would be useful, the option could be modified to also accept four points directly, to save on the overhead of a function call if the points never change.

If the option is not passed to the Kinetic.Image constructor, I fall back to the regular image rendering behavior of KineticJS.

The rendering code starts by splitting the polygon formed by the four target points into four triangles, like this:

![quadrilateral](https://f.cloud.github.com/assets/488309/721395/54f25438-dfe0-11e2-848a-5a322c3d949c.png)

The middle point is where the bimedians (drawn in light gray) meet. The triangles are drawn in black.

I assign (u,v) vertex coordinates to these target points (x,y), so that the four corners of the image are mapped to the four outside points of the target quadrilateral, and the middle of the image is mapped to the intersection of the bimedians inside of the target quadrilateral.

To render the triangles, I find the transformation matrix I need by solving the system of equations determined by the three texture coordinates (source), and the three KineticJS coordinates (target). I save the canvas context's current state, apply the transformation, render only the current triangular section of the image (using clipping), and restore the canvas context's previous state. This is done once for each triangle.