【问题标题】:Moving an object randomly on keypress在按键上随机移动对象
【发布时间】:2018-04-11 03:40:34
【问题描述】:

我想在按键时随机移动一个对象(具体来说是空格键)。但是,我是 JS 的新手。我无法实现完全的随机性。有人可以在这段代码中帮助我实现这一目标吗?而且,当我按下空格键时,图像会变大,但当我使用鼠标时,图像会变小。我希望图像总是很小。

编辑1:为了实现随机性,我使用了一些绝对值。所以有一个随机性起作用的范围。我想消除对绝对值的依赖。

当我使用鼠标向上、向下事件时,图像变小了。

<!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>

【问题讨论】:

  • 我看不到图像变大了?该代码似乎有效。究竟是什么不工作?
  • 我更新了您的 jQuery 参考以使用 CDN,并将代码放在 sn-p.xml 中。如您所见,它工作正常。请编辑您的问题,详细说明您认为此代码不能满足您要求的原因。
  • 根据我的观察编辑
  • 现在我已经添加了鼠标移动的代码。请立即检查,尺寸有变化

标签: javascript jquery html html5-canvas


【解决方案1】:

嗯,这个版本适合我。添加imgWidthimgHeight vars,而不是数值,为每个画布重绘添加宽度和高度,并固定img在按键上的位置。

    <!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>

【讨论】:

  • 非常感谢!!不过,使用空格键时图像更大,但使用鼠标时图像更小
  • Thanx Max... 但是,我有一个疑问。如果我按鼠标然后按键盘,它工作正常。但是,如果我一开始使用键盘,它似乎不起作用。为什么这样?以及如何解决这个问题?
  • 它按预期工作。但是与页面上的任何其他元素一样,您应该首先关注它,然后它才会做出反应。因此,当您首先单击画布时,您会自动聚焦它,因此任何连续的按键都可以工作,但是如果您希望画布最初对按键做出反应,则必须以编程方式对其进行聚焦:$("#canvas").focus();
【解决方案2】:

如果您想这样做,您必须将您的128, 120 设置为始终处于平局状态。您只需在鼠标移动时设置此宽度和高度。也许您应该使宽度和高度取决于用户的屏幕尺寸,例如window.innerWidth

var img = new Image();
      img.onload = function() {
        ctx.drawImage(img, 0, 0, 128, 120);
      };
      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, 128, 120);
        }

      }
      

      $("#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);
      }));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="canvas" width=1300 height=800 tabindex='1'></canvas>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-13
    • 2014-01-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多