【问题标题】:Making an object move on canvas in JavaScript在 JavaScript 中使对象在画布上移动
【发布时间】:2017-04-19 13:23:45
【问题描述】:

我正在尝试用 JavaScript 制作一个简单的游戏,您可以在其中使用箭头键在画布上移动一个对象(圆/球)。我花了很多时间研究和编码,但到目前为止没有运气,所以我希望你们能帮助我。现在,我只是尝试使用箭头键 [上、下、左、右] 来移动对象/球。任何人都能够弄清楚,为什么这不起作用?非常感谢您。

var canvas = document.getElementById("mycanvas");
var ctx = canvas.getContext("2d");

canvas.width = canvas.height = 500;

//the circle
function circle() {
    ctx.beginPath();
    ctx.arc(50, 50, 25, 0, Math.PI * 2, true);
    ctx.fillStyle = "blue";
    ctx.fill();
}

circle();

//move function for going left
window.addEventListener("keydown", function(event) {
    if (event.keyCode == 37) {
      circle.x = 1;
    }
})

【问题讨论】:

  • 所以移动圆圈...答案就在这一行(ctx.arc(50, 50, 25, 0, Math.PI * 2, true);

标签: javascript canvas addeventlistener


【解决方案1】:

你可以通过以下方式完成这样的运动......

var canvas = document.getElementById("mycanvas");
var ctx = canvas.getContext("2d");
var x = 50,
    y = 50,
    radius = 15,
    speed = 3;

function circle() {
    ctx.beginPath();
    ctx.arc(x, y, radius, 0, Math.PI * 2, true);
    ctx.fillStyle = "#07C";
    ctx.fill();
}

function draw() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    circle();
    requestAnimationFrame(draw);
}

draw();

window.addEventListener("keydown", function(e) {
    switch (e.key) {
        case 'ArrowUp':
            if (y > radius) y -= speed;
            break;
        case 'ArrowDown':
            if (y < canvas.height - radius) y += speed;
            break;
        case 'ArrowLeft':
            if (x > radius) x -= speed;
            break;
        case 'ArrowRight':
            if (x < canvas.width - radius) x += speed;
            break;
    }
});
canvas {
  border: 1px solid black;
}
&lt;canvas id="mycanvas" width="200" height="200"&gt;&lt;/canvas&gt;

抱歉没有给出任何解释

【讨论】:

  • 确实如此。我不确定我是否完全理解您的解决方案(我对编码/编程非常陌生),但会确保彻底研究它。非常感谢您的宝贵时间。
  • @thesystem 如果对您有任何帮助,请考虑接受答案:)
  • @thesystem 哈哈..不用担心。谢谢 :) 哦.. 看,现在你也可以投票了 :)
  • @thesystem 你也是 :-)
  • 为了顺利移动stackoverflow.com/questions/32365542/body-animation-isnt-smooth/…(现在有点老了,应该更新为evt.key但基本逻辑仍然存在)
猜你喜欢
  • 2014-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多