2D Vector Dot Product 




Dot Product:Red Length relative to green =Blue Dot Green (Length of Green) squared = 0 


This is an introduction to the 2D Vector Dot Product using javascript and an HTML5 canvas element, so you can view the source for this page and see how everything is done. 
If you have to manipulate lines in any way, the Dot Product is the first thing to try using because it is very easy to calculate. Computers are relatively slow at calculating trigonometric functions. Calculating line length requires a squareroot call which is also slow. This can sometimes be avoided if the calculations are ordered carefully.
The dot product is the sum of products of the vector elements, so for two 2D vectors v1=(dx1,dy1) and v2=(dx2,dy2) the Dot Product is:
Dot(v1,v2)=(dx1*dx2)+(dy1*dy2)If the two vectors are both Unit Vectors (length=1) then the Dot Product will vary from 1 to +1 inclusive (written [1,1]).
If you're more used to Trigonometry, the Dot Product is the lengths of the two vectors multiplied together and to the cosine of the angle between the vectors:
 If the Dot Product is +1, the unit vectors are both pointing in the same direction.
 If the Dot Product is zero, the unit vectors are perpendicular (at rightangles to each other).
 If the Dot Product is 1, the unit vectors are pointing in opposite directions.
A•B = ABcos(θ)
So dividing the Dot Product by the length of one vector gives the projection onto the other vector as shown:
The line colours here are equivalent to those in the interactive diagram.
(A•B) = Acos(θ)
BNote that the value calculated in the interactive diagram is the relative length of the red line to the green line which avoids the need for a squareroot in the length calculation.
Red Length relative to A =(Blue Dot Green) ÷ ((Length of Green) squared)
=(A•B) ÷ (A.dx*A.dx + A.dy*A.dy)
=(A.dx*B.dx + A.dy*B.dy)
(A.dx*A.dx + A.dy*A.dy)This value will vary in the range [0,1] as long as the red line is within the green line.
If this value was multiplied by the length of the green line, that [0,1] range would become [0,length of green].
So dividing by the length squared avoided a square root and gave a unit interval that can be mapped (simply by multiplying) for other uses.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.