首页 > 解决方案 > 如何使用动画移动画布上的元素?

问题描述

我一直在寻找如何使用 JavaScript 在画布上移动某个正方形,但没有找到太多。我已经完成了一个删除自身并在每一帧中替换自身的方法,但我希望它更平滑和动画。这是我的代码:

<canvas id="myCanvas" width="200" height="100" style="border:1px solid grey;"></canvas><br />
<button onclick="#">Move Up</button>
<script>
canvas = document.getElementById("myCanvas");
  ctx = canvas.getContext("2d");
  ctx.fillStyle = "#FF0000";
  ctx.fillRect(20, 60, 20, 20);
</script>

到目前为止,按钮什么也没做,我可以添加一个可以移动方块的功能吗?(在这种情况下)

标签: javascripthtmlcanvasmove

解决方案


要制作流畅的动画,请检查该requestAnimationFrame功能(https://developer.mozilla.org/fr/docs/Web/API/Window/requestAnimationFrame)。

这是您的代码示例:

canvas = document.getElementById('myCanvas');
ctx = canvas.getContext('2d');

var squareY = 60;
var isButtonPressed = false;

ctx.fillStyle = '#FF0000';
ctx.fillRect(20, squareY, 20, 20);

function moveUp() {
  window.requestAnimationFrame(moveUp);

  if (isButtonPressed) {
    squareY -= 10 / 16;
  }

  squareY = Math.max(squareY, 5);

  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fillStyle = '#FF0000';
  ctx.fillRect(20, squareY, 20, 20);
}

function onMouseUp() {
  isButtonPressed = false;
}

function onMouseDown() {
  isButtonPressed = true;
}
canvas = document.getElementById('myCanvas');
ctx = canvas.getContext('2d');

var squareY = 60;
var isButtonPressed = false;

ctx.fillStyle = '#FF0000';
ctx.fillRect(20, squareY, 20, 20);

function moveUp() {
  window.requestAnimationFrame(moveUp);

  if (isButtonPressed) {
    squareY -= 10 / 16;
  }

  squareY = Math.max(squareY, 5);

  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fillStyle = '#FF0000';
  ctx.fillRect(20, squareY, 20, 20);
}

function onMouseUp() {
  isButtonPressed = false;
}

function onMouseDown() {
  isButtonPressed = true;
}

window.addEventListener('keydown', function (e) {
  if (e.key == 'ArrowUp') {
    // if the arrow key is pressed
    squareY -= 10 / 16;
  }
});

moveUp();
<canvas id="myCanvas" width="200" height="100" style="border:1px solid grey;"></canvas><br />
<button onmousedown="onMouseDown()" onmouseup="onMouseUp()">Move Up</button>
<script>
</script>


推荐阅读