Moving an object randomly on keypress

I want to move an object randomly on keypress (spacebar to be specific). However, I am new to JS. I couldn't achieve complete randomness. Can somebody help me in this code to achieve that? And also, when I press the spacebar the image is bigger, but when I use mouse the image becomes smaller. I want the image to be small always.

Edit 1 : To achieve randomness, I have used some absolute value. so there is a range within which the randomness works. I want to remove the dependency on absolute value.

when I use mouse up, down events, the image becomes smaller.

<!doctype html>
<html>

<head>
  <link rel="stylesheet" type="text/css" media="all" href="css/reset.css" />
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

  <style>
    body {}
    
    canvas {
      border: 1px;
    }
  </style>

  <script>
    $(function() {


      var img = new Image();
      img.onload = function() {
        ctx.drawImage(img, 0, 0);
      };
      img.src = "http://www.earthtimes.org/newsimage/eating-apples-extended-lifespan-test-animals-10-per-cent_183.jpg";

      var canvas = document.getElementById("canvas");
      var ctx = canvas.getContext("2d");
      var canvasOffset = $("#canvas").offset();
      var offsetX = canvasOffset.left;
      var offsetY = canvasOffset.top;
      var canvasWidth = canvas.width;
      var canvasHeight = canvas.height;
      var isDragging = false;


function handleMouseDown(e){
  canMouseX=parseInt(e.clientX-offsetX);
  canMouseY=parseInt(e.clientY-offsetY);
  // set the drag flag
  isDragging=true;
    }

function handleMouseUp(e){
  canMouseX=parseInt(e.clientX-offsetX);
  canMouseY=parseInt(e.clientY-offsetY);
  // clear the drag flag
  isDragging=false;
}

function handleMouseOut(e){
  canMouseX=parseInt(e.clientX-offsetX);
  canMouseY=parseInt(e.clientY-offsetY);
  // user has left the canvas, so clear the drag flag
   //isDragging=false;
}

      function handleMouseMove(e) {
        canMouseX = parseInt(e.clientX - offsetX);
        canMouseY = parseInt(e.clientY - offsetY);
        // if the drag flag is set, clear the canvas and draw the image
        if (isDragging) {
          ctx.clearRect(0, 0, canvasWidth, canvasHeight);
          ctx.drawImage(img, canMouseX - 128 / 2, canMouseY - 120 / 2, 128, 120);
        }
      }

      function handleKeyPress(e) {

        if (e.which == 32) {
          canKeybX = Math.random() * 500 * Math.random();
          canKeybY = Math.random() * 400 * Math.random();
          ctx.clearRect(0, 0, canvasWidth, canvasHeight);
          ctx.drawImage(img, canKeybX, canKeybY);
        }

      }
      

      $("#canvas").mousedown(function(e){handleMouseDown(e);});
      $("#canvas").mouseout(function(e){handleMouseOut(e);});
      $("#canvas").mouseup(function(e){handleMouseUp(e);});
      $("#canvas").mousemove(function(e) {
        handleMouseMove(e);
      });
      $("#canvas").keydown((function(e) {
        handleKeyPress(e);
      }));

    }); // end $(function(){});
  </script>

</head>

<body>
  <canvas id="canvas" width=1300 height=800 tabindex='1'></canvas>
</body>

</html>

Answers 1

  • Well, this edition works for me. Add imgWidth imgHeight vars, instead of numerical values, add width and height to each canvas redraw, and fixed positioning of img on keypress.

        <!doctype html>
        <html>
        
        <head>
          <link rel="stylesheet" type="text/css" media="all" href="css/reset.css" />
          <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        
          <style>
            body {}
            
            canvas {
              border: 1px;
            }
        
          </style>
        
          <script>
            $(function() {
        
              var imgWidth = 128;
              var imgHeight = 120;
        
              var img = new Image();
              img.onload = function() {
                ctx.drawImage(img, 0, 0, imgWidth, imgHeight);
              };
              img.src = "http://www.earthtimes.org/newsimage/eating-apples-extended-lifespan-test-animals-10-per-cent_183.jpg";
              var canvas = document.getElementById("canvas");
              var ctx = canvas.getContext("2d");
              var canvasOffset = $("#canvas").offset();
              var offsetX = canvasOffset.left;
              var offsetY = canvasOffset.top;
              var canvasWidth = canvas.width;
              var canvasHeight = canvas.height;
              var isDragging = false;
        
        
        function handleMouseDown(e){
          canMouseX=parseInt(e.clientX-offsetX);
          canMouseY=parseInt(e.clientY-offsetY);
          // set the drag flag
          isDragging=true;
            }
        
        function handleMouseUp(e){
          canMouseX=parseInt(e.clientX-offsetX);
          canMouseY=parseInt(e.clientY-offsetY);
          // clear the drag flag
          isDragging=false;
        }
        
        function handleMouseOut(e){
          canMouseX=parseInt(e.clientX-offsetX);
          canMouseY=parseInt(e.clientY-offsetY);
          // user has left the canvas, so clear the drag flag
           //isDragging=false;
        }
        
              function handleMouseMove(e) {
                canMouseX = parseInt(e.clientX - offsetX);
                canMouseY = parseInt(e.clientY - offsetY);
                // if the drag flag is set, clear the canvas and draw the image
                if (isDragging) {
                  ctx.clearRect(0, 0, canvasWidth, canvasHeight);
                  ctx.drawImage(img, canMouseX - (imgWidth / 2), canMouseY - (imgHeight / 2), imgWidth, imgHeight);
                }
              }
        
              function handleKeyPress(e) {
        
                if (e.which == 32) {
                  canKeybX =  (canvasWidth-imgWidth) * Math.random();
                  canKeybY = (canvasHeight-imgHeight) * Math.random();
                  ctx.clearRect(0, 0, canvasWidth, canvasHeight);
                  ctx.drawImage(img, canKeybX, canKeybY, imgWidth, imgHeight);
                }
        
              }
              
        
              $("#canvas").mousedown(function(e){handleMouseDown(e);});
              $("#canvas").mouseout(function(e){handleMouseOut(e);});
              $("#canvas").mouseup(function(e){handleMouseUp(e);});
              $("#canvas").mousemove(function(e) {
                handleMouseMove(e);
              });
              $("#canvas").keydown((function(e) {
                handleKeyPress(e);
              }));
        
            }); // end $(function(){});
          </script>
        
        </head>
        
        <body>
          <canvas id="canvas" width=1300 height=800 tabindex='1'></canvas>
        </body>
        
        </html>


Related Articles