2D Vector Dot Product 




Dot Product: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(θ)
B
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.