HTML5 Game - Canvas Animation Pythagorean Theorem

Introduction

The following code creates a couple of rectangles, randomly positions them, and then calculates and prints the distance between them.

Demo

ResultView the demo in separate window

<!doctype html>  
<html>  
    <body>  
     <canvas id="canvas" width="400" height="400"></canvas>  
     <script>  
     window.onload = function () {  
       let canvas = document.getElementById('canvas'),  
           context = canvas.getContext('2d');  
     /*from w  ww  .jav a  2  s  .  c om*/
       //Create a black square, assign random position.  
       let rect1 = {  
         x: Math.random() * canvas.width,  
         y: Math.random() * canvas.height  
       };  
       context.fillStyle = "#000000";  
       context.fillRect(rect1.x - 2, rect1.y - 2, 4, 4);  
     
       //Create a red square, assign random position.  
       let rect2 = {  
         x: Math.random() * canvas.width,  
         y: Math.random() * canvas.height  
       };  
       context.fillStyle = "#ff0000";  
       context.fillRect(rect2.x - 2, rect2.y - 2, 4, 4);  
     
       //Calculate the distance between the two squares.  
       let dx = rect1.x - rect2.x,  
           dy = rect1.y - rect2.y,  
           dist = Math.sqrt(dx * dx + dy * dy);  
     
       console.log("distance: " + dist);  
     };  
     </script>  
    </body>  
   </html>

Related Topic