javascript - 如何使用动画移动画布上的元素?
问题描述
我一直在寻找如何使用 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>
到目前为止,按钮什么也没做,我可以添加一个可以移动方块的功能吗?(在这种情况下)
解决方案
要制作流畅的动画,请检查该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>
推荐阅读
- c# - Winform如何改变调用重绘事件的调整大小的方式
- javascript - 如何在每次页面加载时仅发出一次 OPTIONS 预检请求?
- android - 我在底部表单布局中创建了 Recyclerview ,我该如何实现 Onclicklistener 方法?
- javascript - 在 firebase 中查询 startAt 和 endAt 的日期
- .net - WCF 格式化程序在尝试反序列化消息时引发异常
- vue.js - 空白页,vue.js 中没有错误
- swift - 如何在 Swift 5.1 中通过“some”在变量或数组中使用关联类型协议?
- r - 如何使用 R 中的 foreach 循环修改共享对象?
- android - 无法使用 Retrofit 和 RxJava2 填充回收器视图
- typescript - 如何使用打字稿将 vue 道具类型设置为用户类数组?