Distance between two points (canvas)

From Devipedia

Jump to: navigation, search

In the original Distance between two points tutorial, we check out the basic equation for finding the distance between two points and demonstrate with this short python program.

from turtle import *
from math import *

setworldcoordinates(-15,-15,15,15)

# define our points
x1 = 12.0
x2 = 2.0
y1 = 8.0
y2 = 3.0

penup()
goto(x1,y1)
pendown()
dot(10, 'red')  # the first point
goto(x2,y2)     # draws a thin line to the second point
dot(10, 'red')  # the second point

# calculate the length of the hypotenuse

c = sqrt( pow((x1-x2),2) + pow((y1-y2),2))

# Draw a line forward the length of c and visually check 
# our result by comparing the length to our original line.

forward(c)  # draws a line from the second point to the right for a distance of c

Here I'll see how close we can come to demonstrating the same thing using the canvas element and javascript. What I am doing here is simply porting the earlier lesson from Python/Turtle.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head> 
	<script src="./js/jquery-1.3.2.min.js" type="text/javascript"></script> 
	<script type="text/javascript"> 
    	$(function(){
            var canvas  = $('#drawonme')[0];
            var ctx     = canvas.getContext('2d');
            ctx.scale(10,10);
 
            var x1 = 12.0;
            var y1 = 8.0;
            var x2 = 2.0;
            var y2 = 3.0;
 
            ctx.beginPath();
            ctx.fillStyle = "red";  
            ctx.arc(x1,y1,1,0, Math.PI * 2,true);
            ctx.arc(x2,y2,1,0, Math.PI * 2,true);
            ctx.fill();
           
            ctx.beginPath();
            ctx.moveTo(x1,y1);
            ctx.lineTo(x2,y2);
            ctx.stroke();
 
            // calculate the length of the hypotenuse
            var c = Math.sqrt( Math.pow((x1-x2),2) + Math.pow((y1-y2),2)) 
 
            // Draw a line forward the length of c and visually check 
            // our result by comparing the length to our original line.
 
            // Draws a line from the second point to the right for the 
            // distance of c. 
            ctx.beginPath();
            ctx.moveTo(x2,y2);
            ctx.lineTo(x2 + c, y2);
            ctx.stroke();
        });
    </script> 
</head> 
<body> 
    <canvas id="drawonme" width="150" height="150">If your browser supported the canvas element you'd see graphics instead of this boring message.</canvas>  
</body> 
</html>	

And this is what it looks like in the browser: http://www.devinvenable.com/static/canvas/

Okay, now that we're warmed up with canvas, let's move on to something a bit more interesting.

Personal tools